本文主要是介绍iOS-实现最简单的画线功能,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
如何在iOS屏幕上画出一条线来?这是一切复杂画线的基础。首先介绍如何运用CGPath来标定区域:
iOS有时候需要判断是否touch到某个图的区域中。这里做了个小示例,通过CGPath创建一个区域,区域是由路径做两点间线段并闭合成的区域,比如这里创建了一个简单的矩形。然后就可以用CGPath相关函数判断点是否在区域里了。
- (void)viewDidLoad {[super viewDidLoad];CGMutablePathRef pathRef=CGPathCreateMutable();CGPathMoveToPoint(pathRef, NULL, 4, 4);CGPathAddLineToPoint(pathRef, NULL, 4, 8);CGPathAddLineToPoint(pathRef, NULL, 10, 4);CGPathAddLineToPoint(pathRef, NULL, 4, 4);CGPathCloseSubpath(pathRef);CGPoint point=CGPointMake(5,7);CGPoint outPoint=CGPointMake(5,10);if (CGPathContainsPoint(pathRef, NULL, point, NO)) {NSLog(@"point in path!");}if (!CGPathContainsPoint(pathRef, NULL, outPoint, NO)) {NSLog(@"outPoint out path!");}
下面介绍如何画线:
首先要有个UIImageView,在本例中声明为成员变量:
@interface PathDemoViewController : UIViewController {UIImageView *imageView;
}
画线的代码:
- (void)viewDidLoad {[super viewDidLoad];imageView=[[UIImageView alloc] initWithFrame:self.view.frame];[self.view addSubview:imageView];self.view.backgroundColor=[UIColor blueColor];UIGraphicsBeginImageContext(imageView.frame.size);[imageView.image drawInRect:CGRectMake(0, 0, imageView.frame.size.width, imageView.frame.size.height)];CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 15.0);CGContextSetAllowsAntialiasing(UIGraphicsGetCurrentContext(), YES);CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 1.0, 0.0, 0.0, 1.0);CGContextBeginPath(UIGraphicsGetCurrentContext());CGContextMoveToPoint(UIGraphicsGetCurrentContext(), 100, 100);CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), 200, 100);CGContextStrokePath(UIGraphicsGetCurrentContext());imageView.image=UIGraphicsGetImageFromCurrentImageContext();UIGraphicsEndImageContext();
}
其中:
CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
设置了线的边缘样式:
原文链接:http://marshal.easymorse.com/archives/4046
这篇关于iOS-实现最简单的画线功能的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!