使用CGPath绘制一条线

And*_*rey 11 iphone core-graphics

如何使用CGPath画一条线?

Eri*_*und 28

由于您没有真正指定如何使用路径绘制线条,我只想举个例子.

使用UIView的drawRect中的路径在左上角和右下角(在iOS上)之间绘制对角线:

- (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);
}
Run Code Online (Sandbox Code Playgroud)


Ann*_*nne 8

theView.h

#import <UIKit/UIKit.h>

@interface theView : UIView {
}

@end
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

创建上面提到的文件.
基于窗口的应用程序:添加新的UIView并将其类更改为View.
基于视图的应用程序:将UIView类更改为View.
最后点击"构建并运行":)

结果:红色对角线.

  • 我不认为你回答了这个问题.OP想要知道如何创建表示一条线的CGPath并绘制该CGPath. (2认同)