我写过这个......
在.h文件中:
#import <UIKit/UIKit.h>
@interface DrawView : UIView {
CGPoint gestureStartPoint,currentPosition;
CGContextRef c;
UIBezierPath *currentPath;
}
@property(nonatomic,retain)UIBezierPath *currentPath;
@end
在.m文件中:
#import "DrawView.h"
@implementation DrawView
@synthesize currentPath;
- (id)initWithFrame:(CGRect)frame {
[self drawRect:CGRectMake(0, 0, 320, 480)];
self = [super initWithFrame:frame];
if (self) {
currentPath = [[UIBezierPath alloc]init];
currentPath.lineWidth=3;
}
return self;
}
- (void)drawRect:(CGRect)rect {
[[UIColor redColor] set];
[currentPath strokeWithBlendMode:kCGBlendModeNormal alpha:1.0];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
currentPosition = [touch locationInView:self];
[currentPath addLineToPoint:(currentPosition)];
[self setNeedsDisplay];
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
gestureStartPoint = [touch locationInView:self];
[currentPath moveToPoint:(gestureStartPoint)];
}
- (void)dealloc {
[super dealloc];
}
@end
我想让用户在iPhone屏幕上绘制图像,然后将该图像用于游戏......但这并没有画任何东西......
答案 0 :(得分:0)
这是因为您的currentPath未分配。 如果您实例化资源[UIView initWithFrame:]中的视图将永远不会被调用。 实现[UIView initWithCoder:]并在那里分配它。
- (void)commonInit
{
currentPath = [[UIBezierPath alloc] init];
currentPath.lineWidth=3;
}
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
[self commonInit];
}
return self;
}
- (id)initWithCoder:(NSCoder*)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self)
{
[self commonInit];
}
return self;
}
或者,如果它是零,你可以在touchesBegan中创建路径。
- (UIBezierPath*)currentPath
{
if (currentPath = nil)
{
currentPath = [[UIBezierPath alloc] init];
currentPath.lineWidth=3;
}
return currentPath;
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
gestureStartPoint = [touch locationInView:self];
[[self currentPath] moveToPoint:(gestureStartPoint)];
}
但是,代码中存在一些问题。
在self = [super initWithFrame:frame]之前调用[self drawRect:CGRectMake(0,0,320,480)]。你不能在那里调用任何方法。您只能在
中编写代码if(self!= nil) { //你的代码 }
currentPath泄漏。以dealloc发布。
永远不要直接调用drawRect。改为调用[UIView setNeedsDisplay]。