在UIGraphicsImageRenderer中添加UIImage

时间:2018-08-05 00:56:52

标签: 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 { _ 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时,图像不会占据路径的界限...

这就是我所拥有的:

这就是我想要的->

(用猫图片代替白色背景):

我在做什么错? 感谢您的回复!

2 个答案:

答案 0 :(得分:1)

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

    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

最终:

答案 1 :(得分:0)

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

相反,使userPicture为超级视图,并向其中添加一个包含紫色边框的frameView子视图。