I wrote some code to create a UIImage with UIBezierPath but it didn\'t work.
Can someone help me find out what\'s wrong with my code?
You can create image with BeizerPath Swift-3 :-
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var imageOutlet: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
let path3 = createBeizePath()
let image:UIImage = UIImage.shapeImageWithBezierPath(bezierPath: path3, fillColor: .red, strokeColor: .black)
imageOutlet.image = image
}
func createBeizePath() -> UIBezierPath
{
let path = UIBezierPath()
//Rectangle path Trace
path.move(to: CGPoint(x: 20, y: 100) )
path.addLine(to: CGPoint(x: 50 , y: 100))
path.addLine(to: CGPoint(x: 50, y: 150))
path.addLine(to: CGPoint(x: 20, y: 150))
return path
}
}
extension UIImage {
class func shapeImageWithBezierPath(bezierPath: UIBezierPath, fillColor: UIColor?, strokeColor: UIColor?, strokeWidth: CGFloat = 0.0) -> UIImage! {
bezierPath.apply(CGAffineTransform(translationX: -bezierPath.bounds.origin.x, y: -bezierPath.bounds.origin.y ) )
let size = CGSize(width: 100 , height: 100)
UIGraphicsBeginImageContext(size)
let context = UIGraphicsGetCurrentContext()
var image = UIImage()
if let context = context {
context.saveGState()
context.addPath(bezierPath.cgPath)
if strokeColor != nil {
strokeColor!.setStroke()
context.setLineWidth(strokeWidth)
} else { UIColor.clear.setStroke() }
fillColor?.setFill()
context.drawPath(using: .fillStroke)
image = UIGraphicsGetImageFromCurrentImageContext()!
context.restoreGState()
UIGraphicsEndImageContext()
}
return image
}
}
Demo App
Reference