Background Image and canvas with pencilKit Swiftui

旧时模样 提交于 2021-02-05 09:01:56

问题


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)
}

回答1:


The Image is not a UIView, you have to use UIImageView for this case

    let imageView = UIImageView(image: UIImage(named: "badmintoncourt"))

    let subView = self.canvasView.subviews[0]
        subView.addSubview(imageView)
        subView.sendSubviewToBack(imageView)


来源:https://stackoverflow.com/questions/65123721/background-image-and-canvas-with-pencilkit-swiftui

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!