我正在尝试将图像 "resizeLayer" 添加到我的 UIView selectedShape 上,方法是将其子分层到 selectedShape

let sublayer = CALayer()
sublayer.bounds = selectedShape.bounds //even when inserted this line, sublayer still doesn't show up
sublayer.frame = selectedShape.frame
sublayer.contents = UIImage(named: "resizeLayer")
selectedShape?.layer.addSublayer(sublayer)

但是当我运行我的代码时,我根本看不到图层

我什至尝试通过 UIView "resizeLayer" 子查看图像 "selectedShape"
let resizeFrame = UIImageView(image: UIImage(named: "resizeLayer"))
resizeFrame.frame = selectedShape.frame
resizeFrame.contentMode = UIViewContentMode.ScaleAspectFill
selectedShape.addSubview(resizeFrame)

但是,"resizeLayer" 仍然没有出现!

仅当我将 "resizeLayer" 添加到整体 View 时才会显示:
let resizeFrame = UIImageView(image: UIImage(named: "resizeLayer"))
resizeFrame.frame = selectedShape.frame
resizeFrame.contentMode = UIViewContentMode.ScaleAspectFill
selectedShape.addSubview(resizeFrame)
self.view.insertSubview(resizeFrame, aboveSubview: selectedShape) //add this line

对此的任何帮助将不胜感激!

如果相关,这就是我制作 selectedShape 的方式
selectedShape = UIView(frame: CGRect(x: 0, y: 0, width: 60, height: 60))
selectedShape.layer.cornerRadius = 10
selectedShape.backgroundColor = UIColor.blueColor()
canvas.addSubview(selectedShape) //canvas is the view I'm adding selectedShape to

This is the image "resizeLayer" that I'm trying to add

蓝色方块是 selectedShapeAs you can see the layer is not showing up.

What I want to happen

最佳答案

您正在将整个框架用于 selectedShape 。您应该只使用 widthheight 因为 xy 应该是 。图像被添加到 selectedShape 中,因此 (0,0) 点位于 selectedShape View 的左上角。

resizeFrame.frame = CGRect(origin: CGPointZero, size: selectedShape.frame.size)

我承认这让我难住了比应有的时间更长的时间。

10-08 05:30