I'm beginner in Swift and I want to add an image to a custom path draw with UIGraphicsImageRenderer
. I show you my code:
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)
My custom path work well but when I add the userPicture
the image take not the bounds of the path...
This is what I have:
and this is what I want:
(replace the white background by the cat picture):
What am I doing wrong?
I solved my question with another solution (add the path to a shapeLayer and it to the mask of 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
final :