3

我想在不使用 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 或遮罩功能。

4

2 回答 2

5

你做的工作比你需要的多。“无效上下文”消息是由在调用[path addClip]之前调用引起的UIGraphicsBeginImageContextWithOptions()UIBezierPath尝试访问线程的当前图形上下文,但您还没有设置一个。

这是获得相同结果的更简单方法。请注意,您根本不需要使用CGContext

UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0.0);

UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:rect byRoundingCorners:UIRectCornerTopLeft|UIRectCornerTopRight cornerRadii:CGSizeMake(self.cornerRadius, self.cornerRadius)];
[path addClip];

[_image drawInRect:rect];

UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
于 2013-05-12T20:12:48.417 回答
1

我想在不使用 QuartzCore 的情况下向 UIImageView 添加圆角以避免性能问题

一种方法是圆角图像而不是 UIImageView 的角。在这里查看我的答案:

https://stackoverflow.com/a/8125604/341994

我们从任何 UIImage 开始,并通过绘制到裁剪的上下文中来圆其角。这不需要“处理时间”并且不会导致性能问题。

注意:在表格视图或其他非常快速的滚动或动画情况下,圆角处的透明度可能会导致性能问题。但这是一个更普遍的问题,与如何完成舍入无关;这与我们必须不断地将移动的形状合成到背景上有关。如果背景是纯色并且您事先知道它将是什么,那么制作圆角区域的不透明图像会更有效有背景的颜色。)

于 2013-05-12T20:34:33.147 回答