使用普通CALayer显示图像或UIImage

25 iphone performance core-animation uiimage ios

我经常读到,在使用大量图像时,使用a CALayer而不是a UIImageView是性能提升.这是有道理的,因为UIImageView在内存中导致3个图像副本,这是Core Animation所需要的.但在我的情况下,我不使用核心动画.

如何将UIImage(或其图像数据)分配给a CALayer然后显示?

Gle*_*wes 54

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;
Run Code Online (Sandbox Code Playgroud)

或者在Swift游乐场(你必须在Playground的资源文件中提供你自己的PNG图像.我正在使用"FrogAvatar"的例子.)

  //: Playground - noun: a place where people can play
import UIKit

if let backgroundImage = UIImage(named: "FrogAvatar") // you will have to provide your own image in your playground's Resource file
{
    let height = backgroundImage.size.height
    let width = backgroundImage.size.width

    let aLayer = CALayer()
    let startFrame = CGRect(x: 0, y: 0, width: width, height: height)

    let aView = UIView(frame: startFrame)
    aLayer.frame = startFrame
    aLayer.contentsScale = aView.contentScaleFactor
    aLayer.contents = backgroundImage.cgImage
    aView.layer.addSublayer(aLayer)
    aView // look at this via the Playground's  eye icon
}
Run Code Online (Sandbox Code Playgroud)

作为嵌入在UIView中的CALayer内容的图像

  • 需要转换为id,因为CGImageRef未在头文件中定义为从id开始,但这就是CALayer的contents属性的定义方式. (5认同)
  • 只是想提一下你应该用`[[UIScreen mainScreen] scale]来划分原始图像大小 (3认同)

nev*_*ing 12

ARC版本需要不同的演员:

self.myView.layer.contents = (__bridge id) self.myImage.CGImage;
Run Code Online (Sandbox Code Playgroud)