方法一(推薦):使用CALayerapp
CALayer *middleBorder = [CALayer layer]; middleBorder.frame = CGRectMake(x, y, width, height); middleBorder.backgroundColor = UIColor.CGColor; [myView.layer addSublayer:middleBorder];
方法二:使用UIImageView(不便於更改)spa
1 - (void)drawLineWithPoint:(CGPoint) startPoint toPoint:(CGPoint)toPoint 2 { 3 CGSize screenSize = [[UIScreen mainScreen] applicationFrame].size; 4 5 UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, screenSize.width, screenSize.height)]; 6 // UIImageView *imageView = [[UIImageView alloc] init]; 7 // imageView.frame = self.contentView.frame; 8 [self.contentView addSubview:imageView]; 9 10 UIGraphicsBeginImageContext(imageView.frame.size); 11 [imageView.image drawInRect:CGRectMake(0, 0, imageView.frame.size.width, imageView.frame.size.height)]; 12 13 //得到處理的上下文 14 CGContextRef context = UIGraphicsGetCurrentContext(); 15 16 //指定直線樣式 17 CGContextSetLineCap(context, kCGLineCapSquare); 18 19 //直線寬度 20 CGContextSetLineWidth(context, 1.0); 21 22 //設置顏色 23 // red:166/255.0 green:177/255.0 blue:186/255.0 24 CGContextSetRGBStrokeColor(context, 246.0/255.0, 247.0/255.0, 247.0/255.0, 1.0); 25 26 //開始繪製 27 CGContextBeginPath(context); 28 29 //畫筆移動到點(31,170) 30 CGContextMoveToPoint(context, startPoint.x, startPoint.y); 31 32 //下一點 33 CGContextAddLineToPoint(context, toPoint.x, toPoint.y); 34 35 //繪製完成 36 CGContextStrokePath(context); 37 38 imageView.image = UIGraphicsGetImageFromCurrentImageContext(); 39 UIGraphicsEndImageContext(); 40 41 // NSLog(@"%f, %f", imageView.frame.size.width, imageView.frame.size.height); 42 }