1

I’m working on a project that allows the user to draw anything on an image .. after the user finishes drawing . It closes the path and erase the content of image enclosed in a path and assign a new rectangular frame with a new image that can be dragged, but it only shows the content inside the erased path. Do you have any idea how can i achieve that ? I’m new to swift ios. and i have the code to erase the content of image.

What i need is :

  1. assign a new image in a resizable rectangular frame
  2. move the frame to resize accordingly so that it only shows the content inside the erased region This is what I’m trying to do

erase the content of image inside bezier Path

assign a new image in rectangular frame

the movable frame should only be visible inside the removed content of image

Jeeyaa
  • 33
  • 6
  • *"I tried masking the bezierpath ..."* -- ***Show us*** what you tried. Don't just say *"I tried something."* Please review [ask]. – DonMag Aug 17 '23 at 13:38
  • Check my Edited Question – Jeeyaa Aug 18 '23 at 04:54
  • You need to focus on a single task at a time. Do you already have code that is "erases the path" part of the image? Do you already have code for "dragging the rectangle corners" to resize / move it? – DonMag Aug 18 '23 at 12:44
  • I have the code to erase the content of image inside the bezierPath .. I need the code of resizable rectangular frame – Jeeyaa Aug 18 '23 at 12:57
  • OK - learn one step at a time. Head over to Google (or your favorite search engine) and search for `swift user resizable view` -- you'll find lots of examples, articles, blog posts, discussions, etc. – DonMag Aug 18 '23 at 13:13
  • Can you at least help me with calculating the CGRect of Erased path ? – Jeeyaa Aug 21 '23 at 07:13
  • You can use `path.bounds` – DonMag Aug 21 '23 at 11:39
  • ok Thanks .. Solved it by using let addSize = 44.0 let sX = userPath.cgPath.boundingBox.origin.x let sY = userPath.cgPath.boundingBox.origin.y let sW = userPath.cgPath.boundingBox.width let sH = userPath.cgPath.boundingBox.height DrawnRect = CGRect(x: sX-CGFloat(24), y: sY-CGFloat(24), width: sW+CGFloat(addSize), height: sH+CGFloat(addSize)) – Jeeyaa Aug 29 '23 at 11:16

1 Answers1

0

Assuming you have your enclosed UIBezierPath

let path = // ... your enclosed UIBezierPath

Create a CAShapeLayer with the closed path

let shapeLayer = CAShapeLayer()
shapeLayer.path = path.cgPath

Create an image layer

let imageLayer = CALayer()
imageLayer.contents = yourImage.cgImage

Apply the shape layer as a mask to the image layer

imageLayer.mask = shapeLayer

Assuming your view is drawingView

UIGraphicsBeginImageContextWithOptions(drawingView.bounds.size, false, 0.0)
drawingView.drawHierarchy(in: drawingView.bounds, afterScreenUpdates: true)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
Anand
  • 4,355
  • 2
  • 35
  • 45