ios 使用简单的 CALayer 显示图像或 UIImage

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1564940/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 16:32:23  来源:igfitidea点击:

Display an image or UIImage with a plain CALayer

iosiphoneperformanceuiimagecore-animation

提问by Glenn Howes

I've often read that using a CALayerrather than a UIImageViewis an performance boost when it comes to heavy image usage. That makes sense, because UIImageViewcauses 3 copies of the image in memory, which is needed for Core Animation. But in my case I don't use Core Animation.

我经常读到,在大量使用图像时,使用 aCALayer而不是 aUIImageView可以提高性能。这是有道理的,因为UIImageView会在内存中生成 3 个图像副本,这是 Core Animation 所需要的。但就我而言,我不使用核心动画。

How can I assign a UIImage(or its image data) to a CALayerand then display it?

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

回答by Glenn Howes

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
}

An image as the content of a CALayer embedded in a UIView

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

回答by nevan king

ARC version requires a different cast:

ARC 版本需要不同的演员表:

self.myView.layer.contents = (__bridge id) self.myImage.CGImage;

回答by Denis Kutlubaev

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