简体   繁体   English

使用普通CALayer显示图像或UIImage

[英]Display an image or UIImage with a plain CALayer

I've often read that using a CALayer rather than a UIImageView is an performance boost when it comes to heavy image usage. 我经常读到使用CALayer而不是UIImageView是一个性能提升,当涉及到大量的图像使用。 That makes sense, because UIImageView causes 3 copies of the image in memory, which is needed for Core Animation. 这是有道理的,因为UIImageView在内存中导致3个图像副本,这是Core Animation所需要的。 But in my case I don't use Core Animation. 但在我的情况下,我不使用核心动画。

How can I assign a UIImage (or its image data) to a CALayer and then display it? 如何将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;

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".) 或者在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
}

作为嵌入在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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM