Logic 1.
- Connect the four dotted lines to draw a dotted box
- CGContextRef is used here
Key points of 2.
Dotted line, starting point to end point, as follows
CGContextMoveToPoint(currentContext, 0, 0); CGContextAddLineToPoint(currentContext, rect.Origin. X + rect.size. Width, 0);Copy the code
Then connect the top, bottom and left 4 points, as shown in the effect picture:
3. Main code (line method implemented in UIView)
#import "XWShaperLyaerView.h" @implementation XWShaperLyaerView - (instancetype)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { self.backgroundColor = [UIColor clearColor]; // Set transparency to look like a dashed box} return self; } // Provide an instance method - (void)reloadViewLayer {[self setNeedsDisplay]; */ - (void)drawRect:(CGRect)rect{[super drawRect:rect]; CGContextRef currentContext = UIGraphicsGetCurrentContext(); / / set the color dotted CGContextSetStrokeColorWithColor (currentContext, [UIColor redColor]. CGColor); CGContextSetLineWidth(currentContext, 3); CGContextMoveToPoint(currentContext, 0, 0); CGContextAddLineToPoint(currentContext, rect.Origin. X + rect.size. Width, 0); // right CGContextMoveToPoint(currentContext, rect.Origin. X + rect.size. Width, 0); CGContextAddLineToPoint(currentContext, rect.origin.x + rect.size.width, rect.origin.y + rect.size.height); // Left CGContextMoveToPoint(currentContext, 0, 0); CGContextAddLineToPoint(currentContext, 0, rect.size.height); // CGContextMoveToPoint(currentContext, 0, rect.sie.height); CGContextAddLineToPoint(currentContext, rect.origin.x + rect.size.width, rect.origin.y + rect.size.height); CGFloat arr[] = {3,3}; CGFloat arr[] = {3,3}; // The last parameter "2" represents the number of permutations. CGContextSetLineDash(currentContext, 0, arr, 2); CGContextDrawPath(currentContext, kCGPathStroke); } @endCopy the code
4. Usage
As follows: Slide on the screen to add a wrapped UIView, you can make a dotted box as you slide
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { CGPoint point = [self getTouchSet:touches]; If (self. ShapType = = XWDrawingShapeScreenshots) {/ / screenshots / / remove cover [self. CoverView removeFromSuperview]; CGFloat x = self.startPoint.x; CGFloat y = self.startPoint.y; CGFloat width = point.x - self.startPoint.x; CGFloat height = point.y - self.startPoint.y; if (width < 0) { width = -width; x = x - width; } if (height < 0) { height = -height; y = y - height; } CGRect rect = CGRectMake(x, y, width, height); XWShaperLyaerView *coverView = [[XWShaperLyaerView alloc] init]; self.coverView = coverView; // Add a view self.coverview.frame = rect; [self addSubview:self.coverView]; [self.coverView reloadViewLayer] [self.coverView reloadViewLayer]; }}Copy the code