缩小图像,将其添加为我的视图层的内容

Make the image smaller which is added as content of my view's layer

我想将图像设置为我的视图内容,但我不希望图像占据整个画面。我希望图像更小。为此,我尝试将 contentsRect 设置为主层的 80%。

 self.layer.contents = UIImage(named: "plus")?.cgImage
 self.layer.contentsRect = self.layer.frame.insetBy(dx: 5, dy: 5)

但这行不通。调试的时候发现,layer的frame是

▿ (256.0, 398.0, 100.0, 100.0)

contectsRect 是

▿ (261.0, 403.0, 90.0, 90.0)

但是还是没有解决问题,就是图片没有变小。谁能告诉我如何解决这个问题。

这是一种方法。

  • 子类UIView
  • 添加“图像”CALayer 作为子图层
  • layoutSubviews()中设置图像图层的内容和框架(或者,添加您自己的函数来设置图像和图层内容)

示例代码:

class Image80View: UIView {
    
    let imgLayer = CALayer()
    var img: UIImage?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        commonInit()
    }
    func commonInit() -> Void {
        layer.addSublayer(imgLayer)
    }
    override func layoutSubviews() {
        super.layoutSubviews()
        if let img = self.img {
            imgLayer.contents = img.cgImage
        }
        // 10% on each side, so 80% of view
        imgLayer.frame = bounds.insetBy(dx: bounds.width * 0.1, dy: bounds.height * 0.1)
    }
    
}

class TestViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let testView = Image80View()
        testView.translatesAutoresizingMaskIntoConstraints = false
        if let img = UIImage(named: "plus") {
            testView.img = img
        }

        view.addSubview(testView)

        NSLayoutConstraint.activate([
            testView.widthAnchor.constraint(equalToConstant: 200.0),
            testView.heightAnchor.constraint(equalTo: testView.widthAnchor),
            testView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            testView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
        ])

        // so we see the view's frame
        testView.backgroundColor = .green
    }
    
}