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
Display an image or UIImage with a plain CALayer
提问by Glenn Howes
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.
我经常读到,在大量使用图像时,使用 aCALayer
而不是 aUIImageView
可以提高性能。这是有道理的,因为UIImageView
会在内存中生成 3 个图像副本,这是 Core Animation 所需要的。但就我而言,我不使用核心动画。
How can I assign a UIImage
(or its image data) to a CALayer
and 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
}
回答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);