首页 > 解决方案 > 在 UIGraphicsImageRenderer 中添加 UIImage

问题描述

我是 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图像时,不要使用路径的边界......

这就是我所拥有的:

这就是我想要的:

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

我究竟做错了什么?

标签: iosswiftuiimageviewuibezierpath

解决方案


我用另一个解决方案解决了我的问题(将路径添加到 shapeLayer 并将其添加到 a 的掩码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

最终的 :


推荐阅读