drawing on the iPhone in objective c [duplicate]
Possible Duplicate:
Drawing on the iPhone in objective c
I have written this...
In the .h file:
#import <UIKit/UIKit.h>
@interface DrawView : UIView {
CGPoint gestureStartPoint,currentPosition;
CGContex开发者_开发百科tRef c;
UIBezierPath *currentPath;
}
@property(nonatomic,retain)UIBezierPath *currentPath;
@end
And in the .m file:
#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
I want to let the user draw an image on the iPhone screen and then use that image for the game... but this doesn't draw anything...
This is because your currentPath is not allocated. If you instantiate the view in the resource [UIView initWithFrame:] will never be called. Implement [UIView initWithCoder:] and allocate it there.
- (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;
}
Alternatively you can make the path in the touchesBegan if it is nil.
- (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)];
}
However, there are some problems in the code.
You call [self drawRect:CGRectMake(0, 0, 320, 480)] before self = [super initWithFrame:frame]. You must not call any method there. You can write your code only inside
if (self ! =nil) { // your code }
currentPath leaks. Release it in dealloc.
Never call drawRect directly. Call [UIView setNeedsDisplay] instead.
精彩评论