我正在尝试在矩形中绘制一些阴影。阴影图像本身约为1px * 26px。
我想到了两种在视图中绘制图像的方法:
//These methods are called in drawRect:
/* Method 1 */
[self.upperShadow drawInRect:rectHigh]; //upperShadow is UIImage
[self.lowerShadow drawInRect:rectLow];
/* Method 2 */
CALayer *shadowTop = [CALayer layer];
shadowTop.frame = rectHigh;
shadowTop.contents = (__bridge id)topShadow; //topShadow is CGImage
[self.layer addSublayer:shadowTop];
CALayer *shadowLow = [CALayer layer];
shadowLow.frame = rectLow;
shadowLow.contents = (__bridge id)lowShadow;
[self.layer addSublayer:shadowLow];
/* Method 3 */
UIImageView *tShadow = [[UIImageView alloc] initWithFrame:rectHigh];
UIImageView *bShadow = [[UIImageView alloc] initWithFrame:rectLow];
tShadow.image = self.upperShadow;
bShadow.image = self.lowerShadow;
tShadow.contentMode = UIViewContentModeScaleToFill;
bShadow.contentMode = UIViewContentModeScaleToFill;
[self addSubview:tShadow];
[self addSubview:bShadow];
当谈到绘画和动画的表现时,我很好奇哪一个更好。从我的基准测试来看,这些图层的绘制速度似乎更快。以下是一些基准测试统计数据:
drawInRect: took 0.00054 secs
CALayers took 0.00006 secs
UIImageView took 0.00017 secs
包含这些阴影的视图将在其上方具有动画的视图(视图本身不是)。应避免任何会降低动画性能的因素。三种方法之间有什么想法吗?
答案 0 :(得分:2)
如果阴影是静态的,那么最好的方法是使用两个UIImageView
。关于如何处理静态图像甚至比CALayer
更聪明(虽然我不知道这是否会在这里产生影响),否则将具有与CALayer
相同的好处,例如拥有所有合成都是在GPU上完成而不是在CPU上完成(如方法2所要求的那样)。