使用普通CALayer显示图像或UIImage
我经常读到使用 CALayer
而不是 UIImageView
是一个性能提升沉重的图像使用。这是有道理的,因为 UIImageView
会导致内存中的3个图像副本,这是Core Animation所需要的。但在我的情况下,我不使用Core Animation。
I've often read that using a CALayer
rather than a UIImageView
is an performance boost when it comes to heavy image usage. That makes sense, because UIImageView
causes 3 copies of the image in memory, which is needed for Core Animation. But in my case I don't use Core Animation.
如何分配 UIImage
(或其图像数据)到 CALayer
然后显示它?
How can I assign a UIImage
(or its image data) to a CALayer
and then display it?
UIImage* backgroundImage = [UIImage imageNamed:kBackName];
CALayer* aLayer = [CALayer layer];
CGFloat nativeWidth = CGImageGetWidth(backgroundImage.CGImage);
CGFloat nativeHeight = CGImageGetHeight(backgroundImage.CGImage);
CGRect startFrame = CGRectMake(0.0, 0.0, nativeWidth, nativeHeight);
aLayer.contents = (id)backgroundImage.CGImage;
aLayer.frame = startFrame;
或在Swift游乐场(您必须在Playground的资源文件中提供您自己的PNG图像。我正在使用FrogAvatar的例子。)
or in a Swift playground (you will have to provide your own PNG image in the Playground's resource file. I'm using the example of "FrogAvatar".)