I want to set an image as my view's content but I don't want the image to take the whole frame. I want the image to be smaller. To achieve that I am trying to set the contentsRect to be 80% of the main layer.
self.layer.contents = UIImage(named: "plus")?.cgImage
self.layer.contentsRect = self.layer.frame.insetBy(dx: 5, dy: 5)
But this doesn't work. When I debugged, I realized, the layer's frame is
▿ (256.0, 398.0, 100.0, 100.0)
and the contectsRect is
▿ (261.0, 403.0, 90.0, 90.0)
But it still didn't solve the problem, meaning the image is not getting smaller. Can anyone tell me how to fix the issue.
Here's one approach.
UIView
CALayer
as a sublayerlayoutSubviews()
set the image layer's content and frame (or, add your own function to set the image and layer content)Example code:
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
}
}