draw a line by using CGPath [closed]
How can I draw a line by using CGPath ?
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);
}
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.
精彩评论