draw a line by using CGPath [closed]

泄露秘密 提交于 2019-12-03 17:04:42

问题


How can I draw a line by using CGPath ?


回答1:


As you didn't really specify more than how to draw a line with a path, I'll just give you an example.

Drawing a diagonal line between the top left corner and the bottom right (on iOS) with a path in a UIView's 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);
}



回答2:


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

Create the files mentioned above.
Window-based app: Add new UIView and change its class to theView.
View-based app: Change the UIView class to theView.
Finally hit 'build and run' :)

Result: Red diagonal line.



来源:https://stackoverflow.com/questions/5434874/draw-a-line-by-using-cgpath

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!