2

I'm trying to draw a red rectangle over a detected barcode, using iOS 7's newest barcode api's. I've managed to pull in the bounds and corners, but I don't quite know how to take that information and apply it to my view.

In the viewDidLoad Method I define the view that I will use to overlay the barcode once found:

    //Initialize Laser View
    laserView = [[UIView alloc] init];
    laserView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleBottomMargin;
    laserView.layer.borderColor = [UIColor redColor].CGColor;
    laserView.layer.borderWidth = 2;
    [self.view addSubview:laserView];

In the didOutputMetadataObjects I prepare my laser view & pull in the barcode bounds and corners:

//Prepare Laser View's frame
CGRect laser = CGRectZero; 

laser = barcodeObject.bounds;
NSLog(@"Bounds: %@", NSStringFromCGRect(barcodeObject.bounds));
NSLog(@"Frame: %@", barcodeObject.corners);

//Update Laser
laserView.frame = laser;

In my latest run, for bounds I got: {{7.0565414, 314.25}, {265.26062, 1.499999}} and for corners I got:

 (

    {
        X = "7.056541";
        Y = "314.25";
    },
        {
        X = "7.056541";
        Y = "315.75";
    },
        {
        X = "272.3172";
        Y = "315.75";
    },
        {
        X = "272.3172";
        Y = "314.25";
    }
)

I want to be able to tightly wrap a cgrect around a barcode. Here's an example of what I'm trying to do:

enter image description here

KingPolygon
  • 4,753
  • 7
  • 43
  • 72
  • What is your question? The bounds is a CGRect. – David Rönnqvist Feb 11 '14 at 21:14
  • For example in a WWDC presentation, a barcode is scanned at an angle, and the overlay recognizes this skew, and tightly wraps around the barcode. The redlaser app does this as well. I've updated my answer with a photo – KingPolygon Feb 11 '14 at 21:38
  • I see, in that case you are not using a rect (since that is always rectangular). Maybe use a UIBezierPath or CGPath? – David Rönnqvist Feb 11 '14 at 21:54

1 Answers1

1

You'll need to construct a CGPath or UIBezierPath path based on those corners and then draw the path.

  • With the CGPath approach, create the path using CGPathCreateMutable. Create the path by using CGPathMoveToPoint to set the starting point and then using CGPathAddLineToPoint to move from there to each corner in turn. When you finish, you can use the path with a CAShapeLayer. Add that layer as a sub-layer in your view.
  • With UIBezierPath, follow the same general approach as with CGPath. Use moveToPoint: to start and addLineToPoint: to draw the shape. Draw the path as usual (commonly in drawRect in a view).
Tom Harrington
  • 69,312
  • 10
  • 146
  • 170