我如何使用CGPath绘制一条线?
我如何使用CGPath绘制一条线?
由于您没有详细说明路径绘制的更多信息,因此我将为您提供一个示例。
在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);
}
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。
最后点击“构建和运行”:)
结果:红色对角线。