0
我的目標是製作一個程序,每當觸摸屏幕時繪製點。這是我到目前爲止有:在iPhone上使用石英2D繪製基本繪圖
頭文件:
#import <UIKit/UIKit.h>
@interface ElSimView : UIView
{
CGPoint firstTouch;
CGPoint lastTouch;
UIColor *pointColor;
CGRect *points;
int npoints;
}
@property CGPoint firstTouch;
@property CGPoint lastTouch;
@property (nonatomic, retain) UIColor *pointColor;
@property CGRect *points;
@property int npoints;
@end
實現文件:
//@synths etc.
- (id)initWithFrame:(CGRect)frame
{
return self;
}
- (id)initWithCoder:(NSCoder *)coder
{
if(self = [super initWithCoder:coder])
{
self.npoints = 0;
}
return self;
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
firstTouch = [touch locationInView:self];
lastTouch = [touch locationInView:self];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
lastTouch = [touch locationInView:self];
points = (CGRect *)malloc(sizeof(CGRect) * ++npoints);
points[npoints-1] = CGRectMake(lastTouch.x-15, lastTouch.y-15,30,30);
[self setNeedsDisplay];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
lastTouch = [touch locationInView:self];
[self setNeedsDisplay];
}
- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 2.0);
CGContextSetStrokeColorWithColor(context, [UIColor blackColor].CGColor);
CGContextSetFillColorWithColor(context, pointColor.CGColor);
for(int i=0; i<npoints; i++)
CGContextAddEllipseInRect(context, points[i]);
CGContextDrawPath(context, kCGPathFillStroke);
}
- (void)dealloc {
free(points);
[super dealloc];
}
@end
當我加載此,點擊一些點,它繪製第一個點通常,然後隨後的點與隨機橢圓(甚至不是圓圈)一起繪製。
另外我還有一個問題:什麼時候是究竟是drawRect
執行?
drawRect在視圖第一次加載時和當你調用setNeedsDisplay時調用 – Daniel 2010-05-05 18:06:30
除了-drawRect:問題之外,你在這裏的確切問題是什麼?堆棧溢出不是爲代碼審查而設計的,而是爲了回答特定的問題。 – 2010-05-06 15:05:52
一般問題是:「它爲什麼不起作用?」。更具體的問題是「我應該在哪裏添加新點以使其工作」。 – Igor 2010-05-06 15:29:29