我有以下代码在我的UIView drawRect上绘制内部阴影:
//add some inner shadow to the card box
CGContextSaveGState(context);
CGMutablePathRef cardPath = CGPathCreateMutable();
CGPathAddRect(cardPath, NULL, CGRectInset(mainRect, -42, -42));
CGPathAddPath(cardPath, NULL, mainPathRef);
CGPathCloseSubpath(cardPath);
// Add the visible paths as the clipping path to the context
CGContextAddPath(context, mainPathRef);
CGContextClip(context);
// Now setup the shadow properties on the context
UIColor *innerShadowColor = [UIColor colorWithWhite:133/255.f alpha:1.0];
CGContextSetShadowWithColor(context, CGSizeMake(0.0f, 1.0f), 30.0f, [[UIColor orangeColor] CGColor]);
// Now fill the rectangle, so the shadow gets drawn
[innerShadowColor setFill];
CGContextSaveGState(context);
CGContextAddPath(context, cardPath);
CGContextEOFillPath(context);
CGContextRestoreGState(context);
// Release the paths
CGPathRelease(cardPath);
CGContextRestoreGState(context);
CGPathRelease(mainPathRef);
问题是这真的很慢。有没有办法加快这段代码的速度?
答案 0 :(得分:3)
如果可能,我会在图像编辑器中创建阴影,将其保存为png,然后根据需要调整大小并平铺。
另一个想法是使用CALayer的shouldRasterize
属性。它将缓存绘图结果并在视图保持不变时使用它。在这种情况下,性能取决于您修改视图内容的频率。