用普通CALayer显示图像或UIImage

我经常读到,使用CALayer而不是UIImageView是一个性能提升,当涉及到沉重的图像使用。 这是有道理的,因为UIImageView导致内存中的3个副本,这是核心animation所需要的。 但在我的情况下,我不使用核心animation。

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

 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游乐场(你将不得不在游乐场的资源文件中提供你自己的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 } 

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

ARC版本需要不同的强制转换:

 self.myView.layer.contents = (__bridge id) self.myImage.CGImage; 
 CALayer *layer = [[CALayer alloc] init]; layer.contents = (__bridge id _Nullable)([UIImage imageNamed:@"REWIFISocketOff"].CGImage);