5 // Created by Christian Brunschen on 01/07/2008.
7 * Copyright 2008 ZXing authors
9 * Licensed under the Apache License, Version 2.0 (the "License");
10 * you may not use this file except in compliance with the License.
11 * You may obtain a copy of the License at
13 * http://www.apache.org/licenses/LICENSE-2.0
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS,
17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * See the License for the specific language governing permissions and
19 * limitations under the License.
22 #import "ScannedImageView.h"
25 @implementation ScannedImageView
27 - (id)initWithFrame:(CGRect)frame {
28 if ((self = [super initWithFrame:frame])) {
29 resultPoints = [[NSMutableArray alloc] initWithCapacity:10];
34 - (id)initWithCoder:(NSCoder *)decoder {
35 if ((self = [super initWithCoder:decoder]) != nil) {
36 resultPoints = [[NSMutableArray alloc] initWithCapacity:10];
41 - (void)drawRect:(CGRect)rect {
42 [super drawRect:rect];
45 // draw the image, scaled to fit, top and center
46 CGSize imageSize = image.size;
47 CGRect bounds = [self bounds];
48 double imageScale = fminf(bounds.size.width / imageSize.width,
49 bounds.size.height / imageSize.height);
50 double dx = (bounds.size.width - imageSize.width * imageScale) / 2.0;
53 CGContextRef ctx = UIGraphicsGetCurrentContext();
54 CGContextSetInterpolationQuality(ctx, kCGInterpolationDefault);
55 CGRect imageRect = CGRectMake(dx, dy,
56 imageSize.width * imageScale,
57 imageSize.height * imageScale);
58 [image drawInRect:imageRect];
60 [[UIColor greenColor] set];
62 if (resultPoints && [resultPoints count]) {
64 if ([resultPoints count] == 2) {
65 CGPoint p0 = [[resultPoints objectAtIndex:0] CGPointValue];
66 CGPoint p1 = [[resultPoints objectAtIndex:1] CGPointValue];
67 CGContextMoveToPoint(ctx, dx + p0.x * imageScale, dy + p0.y * imageScale);
68 CGContextAddLineToPoint(ctx, dx + p1.x * imageScale, dy + p1.y * imageScale);
69 CGContextSetLineWidth(ctx, 4.0);
70 CGContextSetLineCap(ctx, kCGLineCapSquare);
71 CGContextStrokePath(ctx);
73 // for each resultPoint, draw it
74 for (NSValue *pointValue in resultPoints) {
75 CGPoint resultPoint = [pointValue CGPointValue];
76 float px = dx + resultPoint.x * imageScale;
77 float py = dy + resultPoint.y * imageScale;
79 CGRectMake(px - R, py - R, 2 * R, 2 * R));
81 CGContextFillPath(ctx);
89 - (void) addResultPoint:(CGPoint)p {
90 [resultPoints addObject:[NSValue valueWithCGPoint:p]];
91 [self setNeedsDisplay];
94 - (void) clearResultPoints {
95 [resultPoints removeAllObjects];
98 - (void) setImage:(UIImage *)newImage {
102 [self clearResultPoints];
103 [self setNeedsDisplay];
113 [resultPoints release];