【发布时间】:2010-05-05 17:28:45
【问题描述】:
我的目标是制作一个在触摸屏幕时绘制点的程序。这是我目前所拥有的:
头文件:
#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 时被调用
-
除了 -drawRect: 问题,您的确切问题是什么? Stack Overflow 不是为代码审查而设计的,而是为回答特定问题而设计的。
-
一般问题是:“为什么它不起作用?”。更具体的问题是“我应该将添加新点的部分放在哪里才能使其工作”?
-
感谢您的澄清。我知道你现在遇到了什么问题。