我需要在一个圆角的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)