使用CoreGraphics在iPhone上绘制简单的线条 [英] Drawing simple lines on iPhone with CoreGraphics

查看:186
本文介绍了使用CoreGraphics在iPhone上绘制简单的线条的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在用户触摸屏幕的位置和触摸结束的位置之间绘制一条直线。我需要多行,因为如果用户重复触摸 - 拖动 - 释放动作,我还需要一个按钮来清除所有行。到目前为止,我有下面的代码,但一旦再次调用,我收到错误:CGContextSetStrokeColor:无效的上下文0x0。此错误重复:CGContextBeginPath,CGContextMoveToPoint,CGContextAddLineToPoint,CGContextDrawPath。

I would like to draw a straight line between where a user touches the screen, and where the touch ends. i need multiple lines, for if the user repeats the touch-drag-release action, and I also need a button to clear all of the lines. So far I have this code below, but once it is called again, I receive the errors: CGContextSetStrokeColor: invalid context 0x0. This error repeats for: CGContextBeginPath, CGContextMoveToPoint, CGContextAddLineToPoint, CGContextDrawPath.

任何想法?

- (void)drawRect:(CGRect)rect {   
    c = UIGraphicsGetCurrentContext();

    CGFloat black[4] = {0, 0, 
                        0, 1};
    CGContextSetStrokeColor(c, black);
    CGContextBeginPath(c);
    CGContextMoveToPoint(c, 100, 100);
    CGContextAddLineToPoint(c, 100, 200);
    CGContextStrokePath(c);
}


推荐答案

完整代码如下。

/* Set the color that we want to use to draw the line */ 
[[UIColor brownColor] set];
/* Get the current graphics context */ 
CGContextRef currentContext =UIGraphicsGetCurrentContext();
/* Set the width for the line */
CGContextSetLineWidth(currentContext,5.0f);
/* Start the line at this point */ 
CGContextMoveToPoint(currentContext,50.0f, 10.0f);
/* And end it at this point */ 
CGContextAddLineToPoint(currentContext,100.0f, 200.0f);
/* Use the context's current color to draw the line */
CGContextStrokePath(currentContext);

这篇关于使用CoreGraphics在iPhone上绘制简单的线条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆