I'm learning about PencilKit.
I have a canvas, and I want to set a background image that we can draw on it.
When I save my canvas, I want my background image to be visible
But I have an error : Cannot convert value of type 'Image' to expected argument type 'UIImage?'
Image("badmintoncourt") is an image from my assets I can't find out how to solve it, but I maybe not in the right way to add a background image to my canvas
struct Home : View {
@State var canvas = PKCanvasView()
@Environment(\.undoManager) private var undoManager
@State var showingAlert = false
var body: some View{
NavigationView{
MyCanvas(canvasView: canvas)
.navigationTitle("Drawing")
.navigationBarTitleDisplayMode(.inline)
}
}
}
struct MyCanvas: UIViewRepresentable {
var canvasView: PKCanvasView
let picker = PKToolPicker.init()
func makeUIView(context: Context) -> PKCanvasView {
self.canvasView.tool = PKInkingTool(.pen, color: .black, width: 15)
self.canvasView.isOpaque = false
self.canvasView.backgroundColor = UIColor.clear
self.canvasView.becomeFirstResponder()
let imageView = Image("badmintoncourt")
let subView = self.canvasView.subviews[0]
subView.addSubview(imageView)
subView.sendSubviewToBack(imageView)
return canvasView
}
func updateUIView(_ uiView: PKCanvasView, context: Context) {
picker.addObserver(canvasView)
picker.setVisible(true, forFirstResponder: uiView)
DispatchQueue.main.async {
uiView.becomeFirstResponder()
}
}
}
Edit : Here is my code to save image :
func SaveImage(){
let image = canvas.drawing.image(from: canvas.drawing.bounds, scale: 1)
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
}
The
Image
is not aUIView
, you have to useUIImageView
for this case