显示图像或UIImage的使用纯的CALayer(Display an image or UIIma

2019-07-27 03:23发布

我经常阅读使用CALayer而不是UIImageView是性能提升,当涉及到重形象的使用。 这是有道理的,因为UIImageView导致内存中的图像,这是需要的Core Animation的3份。 但对我来说,我不使用核心动画。

我如何分配UIImage (或其图像数据)到CALayer ,然后显示呢?

Answer 1:

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;

或在操场斯威夫特(你必须提供在操场上的资源文件中自己的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