如果你想UIImage
(您可以将其与UIImageView
), 您可以使用UIGraphicsImageRenderer
:
private func image(with path: UIBezierPath, size: CGSize) -> UIImage {
return UIGraphicsImageRenderer(size: size).image { _ in
UIColor.blue.setStroke()
path.lineWidth = 2
path.stroke()
}
}
这是在 iOS 10 中引入的。如果您需要支持早期的 iOS 版本,可以使用UIGraphicsGetImageFromCurrentImageContext
:
private func image(with path: UIBezierPath, size: CGSize) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(size, false, 0)
UIColor.blue.setStroke()
path.lineWidth = 2
path.stroke()
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
或者,您可以绕过UIImage
如果你愿意的话,只需定义一个UIView
子类具有CAShapeLayer
:
@IBDesignable
class ShapeView: UIView {
@IBInspectable var lineWidth: CGFloat = 1 { didSet { shapeLayer.lineWidth = lineWidth } }
@IBInspectable var strokeColor: UIColor = #colorLiteral(red: 0, green: 0, blue: 1, alpha: 1) { didSet { shapeLayer.strokeColor = strokeColor.cgColor } }
@IBInspectable var fillColor: UIColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 0) { didSet { shapeLayer.fillColor = fillColor.cgColor } }
var path: UIBezierPath? { didSet { shapeLayer.path = path?.cgPath } }
private let shapeLayer = CAShapeLayer()
override init(frame: CGRect) {
super.init(frame: frame)
configure()
}
convenience init() {
self.init(frame: .zero)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configure()
}
/// Add and configure the view.
///
/// Add and configure shape.
private func configure() {
layer.addSublayer(shapeLayer)
shapeLayer.strokeColor = self.strokeColor.cgColor
shapeLayer.fillColor = self.fillColor.cgColor
shapeLayer.lineWidth = self.lineWidth
}
// just add some path so if you used this in IB, you'll see something
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
shapeLayer.path = UIBezierPath(ovalIn: bounds.insetBy(dx: lineWidth / 2, dy: lineWidth / 2)).cgPath
}
}