Ios 在UIGraphicsSimageRenderer中添加UIImage

Ios 在UIGraphicsSimageRenderer中添加UIImage,ios,swift,uiimageview,uibezierpath,Ios,Swift,Uiimageview,Uibezierpath,我是Swift的初学者,我想用UIGraphicsImageRenderer将图像添加到自定义路径绘制中。我向您展示我的代码: let size = CGSize(width:newWidth , height:height) let f = UIGraphicsImageRendererFormat.default() f.opaque = false let r = UIGraphicsImageRenderer(size:size, format: f) let im = r.image

我是Swift的初学者,我想用
UIGraphicsImageRenderer
将图像添加到自定义路径绘制中。我向您展示我的代码:

let size = CGSize(width:newWidth , height:height)
let f = UIGraphicsImageRendererFormat.default()
f.opaque = false
let r = UIGraphicsImageRenderer(size:size, format: f)
let im = r.image { _ in
    let leftUpPath = UIBezierPath()
    leftUpPath.move(to: CGPoint(x: 0, y: 0))
    leftUpPath.addArc(withCenter: CGPoint(x: cornerRadiusView, y: cornerRadiusView),
                      radius: cornerRadiusView,
                      startAngle: .pi * 3 / 2,
                      endAngle: .pi,
                      clockwise: false)
    leftUpPath.addLine(to: CGPoint(x: 0, y: height))
    leftUpPath.addLine(to: CGPoint(x: newWidth - cutPicture, y: height))
    leftUpPath.addLine(to: CGPoint(x: newWidth, y: 0))
    leftUpPath.addLine(to: CGPoint(x: cutPicture, y: 0))
    UIColor(rgb : 0xffffff).setFill()
    leftUpPath.fill()
}
let iv = UIImageView(image:im)
iv.frame.origin = CGPoint(x: 0, y: 0)
iv.clipsToBounds = true

let userPicture = UIImageView(image: picture)
userPicture.frame = iv.bounds
userPicture.clipsToBounds = true

iv.addSubview(userPicture)
cardView.addSubview(iv)
我的自定义路径工作得很好,但是当我添加
userPicture
时,图像不会占用路径的边界

这就是我所拥有的:

这就是我想要的:

(将白色背景替换为cat图片):


我做错了什么

子视图的内容始终显示在其所有祖先的内容之上。您使
userPicture
成为
iv
的子视图,因此
userPicture
的内容显示在
iv
的内容之上。
userPicture
的内容是cat图片。
iv
的内容是紫色边框。因此,猫的图片出现在紫色框架的顶部


相反,将
userPicture
设为superview,并将
frameView
子视图添加到包含紫色边框的视图中。

我用另一个解决方案解决了我的问题(将路径添加到shapeLayer,并将其添加到
UIImageView
的遮罩中):

最终:


要添加当前结果和预期结果吗?:)剪裁到边界仅意味着
UIImageView
将防止图像“过度填充”视图的边界bounds@Glenn完成!用猫图片替换白色背景是我想要的!感谢您的回复,当我这样做时,这总是一样的,图片溢出
iv
路径。。
    let path = UIBezierPath()
    path.move(to: CGPoint(x: 0, y: 0))
    path.addArc(withCenter: CGPoint(x: cornerRadiusView, y: cornerRadiusView),
                radius: cornerRadiusView,
                startAngle: .pi * 3 / 2,
                endAngle: .pi,
                clockwise: false)
    path.addLine(to: CGPoint(x: 0, y: height))
    path.addLine(to: CGPoint(x: newWidth - cutPicture, y: height))
    path.addLine(to: CGPoint(x: newWidth, y: 0))
    path.addLine(to: CGPoint(x: cutPicture, y: 0))
    path.close()

    let shapeLayer = CAShapeLayer()
    shapeLayer.frame = customShape.bounds
    shapeLayer.path = path.cgPath
    shapeLayer.fillColor = UIColor.red.cgColor
    customShape.layer.mask = shapeLayer;
    customShape.layer.masksToBounds = true;
    customShape.image = userPicture
    customShape.contentMode = .scaleAspectFill