我需要在圆形CGRect中放置背景图像。
我可以使用下面的代码使 CGRect 的一角变圆。
let cornerRadius = CGSize(width: 4.0, height: 4.0)
let bezierPath = UIBezierPath(roundedRect: barRect, byRoundingCorners: UIRectCorner(rawValue: UIRectCorner.topLeft.rawValue | UIRectCorner.topRight.rawValue), cornerRadii: cornerRadius)
context.addPath(bezierPath.cgPath)
context.fillPath()
我可以在CGRect中绘制如下所示的图像。
context.draw(image, in: barRect)
但是,我不能绕过路径的拐角,因为我必须使用fillPath()
并且它使背景为纯色。
试试这个扩展:
extension UIImage {
public func imageWithRounded(corners theCorners: UIRectCorner, radius: CGFloat) -> UIImage {
let cornerRadius = CGSize(width: radius, height: radius)
let rect = CGRect(origin: .zero, size: size)
let renderer = UIGraphicsImageRenderer(size: size)
let img = renderer.image { ctx in
UIBezierPath(roundedRect: rect, byRoundingCorners: theCorners, cornerRadii: cornerRadius).addClip()
draw(in: rect)
}
return img
}
}
并像这样使用它:
guard let img = UIImage(named: "myImage") else { return }
let roundedImage = img.imageWithRounded(corners: [.topLeft, .topRight], radius: 20.0)