我有一个UIImageView(完整框架和矩形),正在使用CGAffineTransform旋转它。 UIImageView的UIImage填充整个框架。当图像旋转并绘制时,边缘出现明显的锯齿。有什么办法可以让它看起来更好吗?很明显它没有与背景进行反锯齿处理。
我有一个UIImageView(完整框架和矩形),正在使用CGAffineTransform旋转它。 UIImageView的UIImage填充整个框架。当图像旋转并绘制时,边缘出现明显的锯齿。有什么办法可以让它看起来更好吗?很明显它没有与背景进行反锯齿处理。
UIAlertView
的圆角。 - Kevin Hirsch新API - iOS 6/7
正如@Chris所指出的那样,它也适用于iOS 6,但直到iOS 7才公开。
自iOS 7以来,CALayer有一个新属性allowsEdgeAntialiasing
,在不为应用程序中所有视图启用它的情况下,该属性完全满足您此时的需求!这是CALayer的一个属性,因此要为UIView启用它,您可以使用myView.layer.allowsEdgeAntialiasing = YES
。
只需在您的图像上添加1像素的透明边框即可
CGRect imageRect = CGRectMake(0, 0, image.size.width, image.size.height);
UIGraphicsBeginImageContextWithOptions(imageRect.size, NO, 0.0);
[image drawInRect:CGRectMake(1,1,image.size.width-2,image.size.height-2)];
image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
请记得设置适当的抗锯齿选项:
CGContextSetAllowsAntialiasing(theContext, true);
CGContextSetShouldAntialias(theContext, true);
CGRect imageRect = CGRectMake(0, 0, self.photo.image.size.width, self.photo.image.size.height);
UIGraphicsBeginImageContextWithOptions(imageRect.size, NO, 0.0);
[self.photo.image drawInRect:CGRectMake(1, 1, self.photo.image.size.width - 2, self.photo.image.size.height - 2)];
self.photo.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
像一些人描述的那样添加Info.plist键对性能有很大影响,如果你使用它,那么基本上是应用于所有地方而不仅仅是你需要的一个地方。
另外,不要只使用UIGraphicsBeginImageContext(imageRect.size);
否则图层会模糊。你必须像我展示的那样使用UIGraphicsBeginImageContextWithOptions
。
我从这里找到了这个解决方案,它非常完美:
+ (UIImage *)renderImageFromView:(UIView *)view withRect:(CGRect)frame transparentInsets:(UIEdgeInsets)insets {
CGSize imageSizeWithBorder = CGSizeMake(frame.size.width + insets.left + insets.right, frame.size.height + insets.top + insets.bottom);
// Create a new context of the desired size to render the image
UIGraphicsBeginImageContextWithOptions(imageSizeWithBorder, NO, 0);
CGContextRef context = UIGraphicsGetCurrentContext();
// Clip the context to the portion of the view we will draw
CGContextClipToRect(context, (CGRect){{insets.left, insets.top}, frame.size});
// Translate it, to the desired position
CGContextTranslateCTM(context, -frame.origin.x + insets.left, -frame.origin.y + insets.top);
// Render the view as image
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
// Fetch the image
UIImage *renderedImage = UIGraphicsGetImageFromCurrentImageContext();
// Cleanup
UIGraphicsEndImageContext();
return renderedImage;
}
用法:
UIImage *image = [UIImage renderImageFromView:view withRect:view.bounds transparentInsets:UIEdgeInsetsZero];