1

我正在尝试通过触摸它来制作一个在屏幕上绘制形状的应用程序。

我可以从一个点到另一个点画一条线 - 但它会在每次新的绘制时擦除。

这是我的代码:

CGPoint location;
CGContextRef context;
CGPoint drawAtPoint;
CGPoint lastPoint;
-(void)awakeFromNib{
    //[self addSubview:noteView];
}

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [[event allTouches] anyObject];
    location = [touch locationInView:touch.view];
    [self setNeedsDisplayInRect:CGRectMake(0, 0, 320, 480)];
}

- (void)drawRect:(CGRect)rect {
    context = UIGraphicsGetCurrentContext();
    [[UIColor blueColor] set];
    CGContextSetLineWidth(context,10);
    drawAtPoint.x =location.x;
    drawAtPoint.y =location.y;
    CGContextAddEllipseInRect(context,CGRectMake(drawAtPoint.x, drawAtPoint.y, 2, 2));
    CGContextAddLineToPoint(context,lastPoint.x, lastPoint.y);
    CGContextStrokePath(context);

    lastPoint.x =location.x;
    lastPoint.y =location.y;
}

感谢你的帮助-

尼尔。

4

3 回答 3

2

正如您所发现的,-drawRect 是您显示视图内容的位置。您只会在屏幕上“看到”您在此处绘制的内容。

这比 Flash 之类的东西要低级得多,在 Flash 中,您可能会在舞台上添加一个包含一条线的影片剪辑,然后在一段时间后将另一个包含一条线的影片剪辑添加到舞台上,现在您会看到 - 两条线!

您将需要做一些工作,并且可能会设置类似..

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { 

    UITouch *touch = [[event allTouches] anyObject]; 
    location = [touch locationInView:touch.view]; 

    [self addNewLineFrom:lastPoint to:location];

    lastPoint = location;

    [self setNeedsDisplayInRect:CGRectMake(0, 0, 320, 480)]; 
}

- (void)drawRect:(CGRect)rect {

    context = UIGraphicsGetCurrentContext();

    for( Line *eachLine in lineArray )
        [eachLine drawInContext:context];

}

我认为您可以看到如何将其充实到您需要的内容。

解决此问题的另一种方法是使用 CALayers。使用这种方法,您根本不会在内部绘制 - - (void)drawRect - 您添加和删除图层,在其中绘制您喜欢的内容,视图将处理将它们合成在一起并根据需要绘制到屏幕上。可能更多您正在寻找的东西。

于 2009-11-04T11:21:31.623 回答
1

每次drawRect调用时,您都会从一张白纸开始。如果您不跟踪之前绘制的所有内容以便再次绘制它,那么您最终只会绘制最新的手指滑动,而不是任何旧的滑动。您必须跟踪所有手指滑动,以便在每次drawRect调用时重新绘制它们。

于 2009-11-04T11:28:58.057 回答
0

您可以绘制图像,然后在您的drawRect:方法中显示图像,而不是重绘每一行。图像将为您累积线条。当然,这种方法使撤消更难实现。

来自iPhone 应用程序编程指南

使用 UIGraphicsBeginImageContext 函数创建一个新的基于图像的图形上下文。创建此上下文后,您可以将图像内容绘制到其中,然后使用 UIGraphicsGetImageFromCurrentImageContext 函数根据您绘制的内容生成图像。(如果需要,您甚至可以继续绘制并生成其他图像。)创建完图像后,使用 UIGraphicsEndImageContext 函数关闭图形上下文。如果您更喜欢使用 Core Graphics,您可以使用 CGBitmapContextCreate 函数来创建位图图形上下文并将图像内容绘制到其中。完成绘制后,使用 CGBitmapContextCreateImage 函数从位图上下文创建 CGImageRef。

于 2009-11-04T13:51:17.377 回答