ImageContext 返回扭曲的图像
Posted
技术标签:
【中文标题】ImageContext 返回扭曲的图像【英文标题】:ImageContext returns image distorted 【发布时间】:2017-09-26 10:20:58 【问题描述】:我正在尝试使图像的角变圆,但 ImageContext 中的图像变形了。
这是我正在采取的步骤:
- (UIImage *)decodeBase64ToImage:(NSString *)strEncodedData
NSURL *url = [NSURL URLWithString:strEncodedData];
NSData* data = [[NSData alloc] initWithContentsOfURL:url];
UIImage* image = [[UIImage alloc] initWithData:data];
UIImage* croppedImage = [self makeRoundedImage:image];
return croppedImage;
- (UIImage *)makeRoundedImage:(UIImage *) image
CGRect frame = CGRectMake(0, 0, image.size.width, image.size.height);
UIGraphicsBeginImageContext(frame.size);
//[[UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, image.size.width, image.size.height) cornerRadius:10.0] addClip];
[image drawInRect:frame];
// Get the image
UIImage *croppedImage = UIGraphicsGetImageFromCurrentImageContext();
// Lets forget about that we were drawing
UIGraphicsEndImageContext();
return croppedImage;
【问题讨论】:
我认为没有必要在 UIImage 的角落。您需要制作 UIImageView 的角。 @YogendraGirase 我不能使用 UIImageView,我需要在一个只能使用 UIImage 的框架中使用它。 你可以在下面查看我的答案。它可能对你有帮助 @YogendraGirase 似乎在 UIImageView 中工作,这两个答案,我认为我之后使用的框架有问题。 【参考方案1】:你可以检查这个方法
-(UIImage *)roundedImage:(UIImage *) roundImage
radius: (float) radius;
CALayer *imageLayer = [CALayer layer];
imageLayer.frame = CGRectMake(0, 0, roundImage.size.width, roundImage.size.height);
imageLayer.contents = (id) roundImage.CGImage;
imageLayer.masksToBounds = YES;
imageLayer.cornerRadius = radius;
UIGraphicsBeginImageContext(roundImage.size);
[imageLayer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *finalRoundedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return finalRoundedImage;
【讨论】:
【参考方案2】:试试这个。
-(UIImage *)imageWithRoundedCorner:(float)cornerRadius Image:(UIImage *)realImage
UIImageView *imageView = [[UIImageView alloc] initWithImage:realImage];
UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, NO, 1.0);
[[UIBezierPath bezierPathWithRoundedRect:imageView.bounds cornerRadius:cornerRadius] addClip];
[realImage drawInRect:imageView.bounds];
imageView.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return imageView.image;
【讨论】:
【参考方案3】:试试这个。,它会解决图像失真的问题..
- (UIImage *)makeRoundedImage:(UIImage *) image
CGRect frame = CGRectMake(0, 0, image.size.width, image.size.height);
UIGraphicsBeginImageContextWithOptions(frame.size, NO, 0);
//[[UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, image.size.width, image.size.height) cornerRadius:10.0] addClip];
[image drawInRect:frame];
// Get the image
UIImage *croppedImage = UIGraphicsGetImageFromCurrentImageContext();
// Lets forget about that we were drawing
UIGraphicsEndImageContext();
return croppedImage;
【讨论】:
我发现了这个问题,我的其他框架没有直接从 ImageContext 接受 UIImage,所以我必须将它转换为 PNG 表示然后它才能工作,但是谢谢!以上是关于ImageContext 返回扭曲的图像的主要内容,如果未能解决你的问题,请参考以下文章