And*_*rew 1 core-graphics cgcontext ios uibezierpath swift
我正在尝试使用提供的 UIBezierPath 创建一个 UIImage。不幸的是,无论我设置什么setLineWidth,结果总是 1 分:
extension UIBezierPath {
func image(fillColor: UIColor, strokeColor: UIColor) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(bounds.size, false, 1.0)
guard let context = UIGraphicsGetCurrentContext() else {
return nil
}
context.setLineWidth(10)
context.setFillColor(fillColor.cgColor)
context.setStrokeColor(strokeColor.cgColor)
self.fill()
self.stroke()
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
Run Code Online (Sandbox Code Playgroud)
在一个带有圆圈的测试项目中尝试这个,例如:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let imageView = UIImageView()
imageView.frame = CGRect(x: 100, y: 100, width: 100, height: 100)
view.addSubview(imageView)
let bezierPath = UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: 100, height: 100))
let image = bezierPath.image(fillColor: UIColor.blue, strokeColor: UIColor.red)
imageView.image = image
}
}
Run Code Online (Sandbox Code Playgroud)
无论我设置什么setLineWidth,它似乎总是 1 分。
您呼叫stroke的UIBezierPath,所以你需要设置lineWidth,使用的财产self.lineWidth = 10。
extension UIBezierPath {
func image(fillColor: UIColor, strokeColor: UIColor) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(bounds.size, false, 1.0)
guard let context = UIGraphicsGetCurrentContext() else {
return nil
}
context.setFillColor(fillColor.cgColor)
self.lineWidth = 10
context.setStrokeColor(strokeColor.cgColor)
self.fill()
self.stroke()
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1096 次 |
| 最近记录: |