我想在不使用 QuartzCore 的情况下向 UIImageView 添加圆角以避免 UIScrollView 中的性能问题,所以我这样解决了它:
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:rect byRoundingCorners:UIRectCornerTopLeft|UIRectCornerTopRight cornerRadii:CGSizeMake(self.cornerRadius, self.cornerRadius)];
[path addClip];
UIGraphicsBeginImageContextWithOptions(rect.size, NO, [[UIScreen mainScreen] scale]);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetBlendMode(UIGraphicsGetCurrentContext( ),kCGBlendModeClear); CGContextSetStrokeColorWithColor(context, [UIColor clearColor].CGColor);
CGContextAddPath(context,path.CGPath);
CGContextClip(context);
CGContextClearRect(context,CGRectMake(0,0,width,height));
[_image drawInRect:rect];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
可悲的是,在 drawRect 中调用,这需要一点处理时间,这会在 UIScrollView 中滚动时产生延迟。因此,我尝试在 dispatch_async 的帮助下在单独的线程中处理它。这消除了滞后,一切都按原样顺利进行。但现在我有另一个问题。我在调试器中收到许多无效的上下文消息,因为当线程异步启动图像处理时,GraphicsContext 并不总是存在。有没有办法处理我的图像中的圆角而不会收到无效的上下文消息?请注意,我不想使用 QuarzCore 的cornerRadius 或遮罩功能。