将图像加载到图层的方法很简单:
CALayer *layer = [[CALayer alloc]init];
layer.contents = (id) [UIImage imageNamed:@"image.png"].CGImage;
然后将图层作为子图层添加到 View 中,例如:
假设你在 View 中
[self.layer addSublayer:layer];
现在我想加载一组图像作为动画,所以最终我会让图像动画化。
所以在实际执行动画之前我测试了以下内容:
[values insertObject:(id)[UIImage imageNamed:path].CGImage atIndex:i];
当然有一个循环运行,将每个图像输入到正确的索引...然后我得到一组 CGImage
.. 用于动画。
我打印了这个数组并看到了这个:
CGImage 0x17d900
CGImage 0x17f4e0
所以值在那里..我没有收到任何错误..但我没有看到图像...
如果您有想法,请告诉我....
最佳答案
这是一段代码片段,对我的一个项目运行良好:
CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath: @"contents"];
animation.calculationMode = kCAAnimationDiscrete;
animation.duration = 1.0;
animation.values = values; // NSArray of CGImageRefs
[layer addAnimation: animation forKey: @"contents"];
但是,我的动画帧和旧 iPhone/iPod 上的图像过大,导致严重的性能问题。如果遇到这种情况,秘诀就是使用预渲染图像(IIRC,它们用私有(private) CABackingStore
类表示)。简而言之,您制作了一个正确大小的 CALayer,它使用 drawInContext:
绘制单个动画帧,然后循环遍历动画帧,向层提供帧图像,将其发送display
并将其内容属性保存到一个数组中。只要您不尝试以任何方式操纵预渲染图像,缓存技术就是安全的:基本上,您只需执行 layer1.contents = layer2.contents
。
除非您确实遇到性能问题,否则不要浪费时间实现上述内容。
关于iPhone CALayer 图像数组内容值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4853929/