My code successful saves a image to the photo gallery however what I drew over that image is not being saved on top of it. So my code needs to save the image and the user input drawing. Right now it just saves the image.
var nextPage = UIButton()
var clear = UIButton()
var submitToDB = UIButton()
var myLayer = CALayer()
var path = UIBezierPath()
var startPoint = CGPoint()
var touchPoint = CGPoint()
var playName = UITextField()
var drawPlace = UIImageView()//The imageview
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = touches.first
if let point = touch?.location(in: drawPlace){
startPoint = point
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = touches.first
if let point = touch?.location(in: drawPlace){
touchPoint = point
}
path.move(to: startPoint)
path.addLine(to: touchPoint)
startPoint = touchPoint
draw()
}
func draw() {
submitToDB.layer.cornerRadius = 0
drawPlace.clipsToBounds = true
drawPlace.isMultipleTouchEnabled = false
let strokeLayer = CAShapeLayer()
strokeLayer.fillColor = nil
strokeLayer.lineWidth = 5
strokeLayer.strokeColor = UIColor.blue.cgColor
strokeLayer.path = path.cgPath
drawPlace.layer.insertSublayer(strokeLayer, below: myLayer)
drawPlace.setNeedsDisplay()
let star:UIImage = UIImage(named: "bb.png")!
let newSize = CGSize(width: star.size.width, height: star.size.height )
UIGraphicsBeginImageContextWithOptions(newSize, false, star.scale)
star.draw(in: CGRect(x: newSize.width/10.6,
y: newSize.height/8,
width: newSize.width/1.2,
height: newSize.height/1.2),
blendMode:CGBlendMode.normal, alpha:1)
let newImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
drawPlace.image = newImage
}
func save() {
guard let selectedImage = drawPlace.image else {
print("Image not found!")
return
}
UIImageWriteToSavedPhotosAlbum(selectedImage, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)
}
I guess I need to somehow save the layer over the image being saved I just don't know how to do that.
You need to make capture from the UIImageView
, so try this:
Add extension to UIView
to make a capture:
extension UIView {
func screenshot() -> UIImage {
return UIGraphicsImageRenderer(size: bounds.size).image { _ in
drawHierarchy(in: CGRect(origin: .zero, size: bounds.size), afterScreenUpdates: true)
}
}
}
After that, change your save()
to this:
func save() {
let image = drawPlace.screenshot()
UIImageWriteToSavedPhotosAlbum(image, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)
}