TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Canvas: move, select, add data to objects

Forums > SwiftUI

Hey, all.

I'm trying to write a Mac app where the user draws rectangles over part of an image, then exports the coords of those rectangles as JSON (part of a CoreML app that I need to provide training data for).

So far I've created a struct to manage the rectangles, with coordinates and a label. I've also created an array of these rect structs.

I am using a ZStack for the image and the Canvas for drawing in. So far I have been able to draw out rectangles using gestures, capturing the start point in onChanged (state var tracks when a new drag starts) and end point in onEnded. In the body of the canvas I loop through the array and pass the rectangle coords to a new path, then context.stroke the path to draw the rectangle.

I've also added a state var "ghost rect" that gets stroked after the array of rects gets drawn, which nicely gives the user a real-time view of the rectangle they're dragging out.

First off, does this seem like the best way to do this? I can't mutate the rects in the array since they're stored in a struct (I tried adding a strokeColor var to change a rect's outline when clicked on). I tried a class, and I could mutate the variables, but the rects didn't get updated until I started drawing a new one, so the hilight color doesn't show when you click on it.

The last thing I need some help on is, I'd like to ask the user to supply a label as soon as they're done drawing it out. Is it as simple as calling .alert? I still am not to the point where I can mutate the rects in the array, but hoping to resolve that.

Here's a short gif of the class version showing the change to a rect's strokeColor not being updated until the ensuing rect drag is started.

3      

Hacking with Swift is sponsored by Blaze.

SPONSORED Still waiting on your CI build? Speed it up ~3x with Blaze - change one line, pay less, keep your existing GitHub workflows. First 25 HWS readers to use code HACKING at checkout get 50% off the first year. Try it now for free!

Reserve your spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.