使用CGPath绘制线条
答
theView.h
#import <UIKit/UIKit.h>
@interface theView : UIView {
}
@end
theView.m
#import "theView.h"
@implementation theView
-(void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
CGContextSetLineWidth(context, 2.0);
CGContextMoveToPoint(context,0,0);
CGContextAddLineToPoint(context,20,20);
CGContextStrokePath(context);
}
@end
创建上述文件。
基于窗口的应用程序:添加新的UIView并将其类更改为该视图。
基于视图的应用程序:将UIView类更改为该视图。
最后点击'建立并运行':)
结果:红色的对角线。
+0
你不应该也释放路径或什么? – 2013-12-17 14:31:55
+2
我不认为你回答了这个问题。 OP想知道如何创建一个代表一条线的CGPath并绘制该CGPath。 – moonman239 2014-12-01 17:41:56
答
由于您没有真正指定如何绘制一条路径,我只给你一个例子。
绘制与路径左上角和右下角(在iOS上)之间的对角线在一个UIView的drawRect:
- (void)drawRect:(CGRect)rect {
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGMutablePathRef path = CGPathCreateMutable();
CGPathMoveToPoint(path, NULL, 0, 0);
CGPathAddLineToPoint(path, NULL, CGRectGetMaxX(rect), CGRectGetMaxY(rect));
CGPathCloseSubpath(path);
CGContextAddPath(ctx, path);
CGContextSetStrokeColorWithColor(ctx,[UIColor whiteColor].CGColor);
CGContextStrokePath(ctx);
CGPathRelease(path);
}
它是如何很难说什么被要求在这里?对于这个问题,还有什么其他解释可以比提问者想知道如何绘制代表一条线的CGPath? – moonman239 2014-12-01 17:47:24
画线有很多种方法。核心图形,石英,OpenGL,SpriteKit,GLKit,SceneKit,GL着色器 - 仅举几例。我们必须猜测OP的意图/首选框架。 – LearnCocos2D 2015-07-05 10:41:49
由于他引用了CGPath,是否安全地使用Core Graphics? – 2016-08-30 04:33:22