Using Barcode Corners to Create CGRect?

1.2k Views Asked by At

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

1

There are 1 best solutions below

0
On

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