Display an image or UIImage with a plain CALayer

2019-01-21 11:33发布

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.

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

3条回答
我只想做你的唯一
2楼-- · 2019-01-21 11:38

ARC version requires a different cast:

self.myView.layer.contents = (__bridge id) self.myImage.CGImage;
查看更多
We Are One
3楼-- · 2019-01-21 11:48
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".)

  //: 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                                                                     
查看更多
Ridiculous、
4楼-- · 2019-01-21 11:54
CALayer *layer = [[CALayer alloc] init];
layer.contents = (__bridge id _Nullable)([UIImage imageNamed:@"REWIFISocketOff"].CGImage);
查看更多
登录 后发表回答