2010-05-05 58 views
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執行?

+0

drawRect在視圖第一次加載時和當你調用setNeedsDisplay時調用 – Daniel 2010-05-05 18:06:30

+0

除了-drawRect:問題之外,你在這裏的確切問題是什麼?堆棧溢出不是爲代碼審查而設計的,而是爲了回答特定的問題。 – 2010-05-06 15:05:52

+0

一般問題是:「它爲什麼不起作用?」。更具體的問題是「我應該在哪裏添加新點以使其工作」。 – Igor 2010-05-06 15:29:29

回答

1

在-touchesEnded:withEvent:,你有下面的代碼:

points = (CGRect *)malloc(sizeof(CGRect) * ++npoints); 
points[npoints-1] = CGRectMake(lastTouch.x-15, lastTouch.y-15,30,30); 

您要重新分配的數組,points,但不能複製在您之前的任何點。這導致您使用隨機未初始化的內存值而不是您保存的CGRects。相反,你可以試試下面的:

CGRect *newPoints = (CGRect *)malloc(sizeof(CGRect) * ++npoints); 
for (unsigned int currentPoint = 0; currentPoint < (npoints - 1); currentPoint++) 
{ 
    newPoints[currentPoint] = points[currentPoint]; 
} 
free(points); 
points = newPoints; 

points[npoints-1] = CGRectMake(lastTouch.x-15, lastTouch.y-15,30,30); 

你也通過分配一個新的數組,其內容之前不會釋放它之前泄漏points陣列。

只要調用-drawRect:,它會在iPhone OS顯示系統需要重新緩存UIView的內容時觸發。正如丹尼爾所說,這通常發生在初始顯示和每當你在UIView上手動調用-setNeedsDisplay時。