当前我正在使用以下代码舍入UIImage:
//round the image
UIImageView *roundView = [[UIImageView alloc] initWithImage:smallImage];
UIGraphicsBeginImageContextWithOptions(roundView.bounds.size, NO, [UIScreen mainScreen].scale);
[[UIBezierPath bezierPathWithRoundedRect:roundView.bounds
cornerRadius:roundView.frame.size.width/2] addClip];
[smallImage drawInRect:roundView.bounds];
UIImage *finalImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
smallImage = finalImage;
//end round image
self.thumbnailView.image=smallImage;
UIImageWriteToSavedPhotosAlbum(smallImage, self, nil, nil); //20kb
UIGraphicsEndImageContext();
然而,这会使圆圈的外侧变白,所以当我按下图像时(如果它被用作UIButton),你可以看到它是一个正方形的图像。有没有办法将UIImage剪辑成一个圆圈,但使其外部透明?任何建议都将不胜感激。
您可以设置UIImageView
的拐角半径,使其像这样取整:-
[yourImageView.layer setCornerRadius:CGRectGetWidth(yourImageView.frame)/2];
你可以增加它使它变小。
无论如何,我不太确定为什么您有两个调用来结束代码段中的图像上下文,尽管理论上上下文本身应该已经是透明的(因为您将NO传递给不透明参数),但如果不是,您总是可以在剪切和绘制图像之前用透明像素填充它
UIGraphicsBeginImageContextWithOptions(roundView.bounds.size, NO, 0.f);
CGContextRef ctx = UIGraphicsGetCurrentContext();
[[UIColor clearColor] set];
CGContextFillRect(ctx, roundView.bounds);
[[UIBezierPath bezierPathWithRoundedRect:roundView.bounds
cornerRadius:roundView.frame.size.width/2] addClip];
[smallImage drawInRect:roundView.bounds];
UIImage *finalImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
我确实在Swift操场上试用了你的代码和添加的填充代码,它们似乎产生了类似的结果,所以我不相信这会解决你的问题,而且你可能没有向我们展示所有可能操纵上下文的代码。
PS!将0传递给scale
会自动使用上下文的正确主屏幕比例;)
编辑:刚刚意识到,你的按钮可能有一个白色背景,你通常不会在图像下看到,但你现在看到了,因为图像是透明的。。。