使用CGPath绘制一条线

12

我如何使用CGPath绘制一条线?


2
这里很难确定被问的是什么?除了询问者想知道如何绘制代表线条的CGPath之外,还有什么其他的问题解释吗? - user749127
有很多种方法可以画一条线。Core Graphics、Quartz、OpenGL、SpriteKit、GLKit、SceneKit、GL Shaders等等。我们必须猜测OP的意图/首选框架。 - CodeSmile
1
他引用了CGPath,那么假设使用Core Graphics是安全的,不是吗? - Shaun Budhram
2个回答

27

由于您没有详细说明路径绘制的更多信息,因此我将为您提供一个示例。

在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);
}

8

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

创建上述提到的文件。
基于Windows的应用程序:添加新的UIView并将其类更改为theView。
基于视图的应用程序:将UIView类更改为theView。
最后点击“构建和运行”:)

结果:红色对角线。


你也应该释放路径或其他内容吗? - Radu Simionescu
2
我认为你没有回答问题。OP想知道如何创建代表线条的CGPath并绘制该CGPath。 - user749127

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接