用手指iOS绘图

时间:2013-09-28 15:08:47

标签: ios objective-c cocoa-touch drawing

我正在编写用户可以用手指画线的应用程序。

这是代码:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{ 
    NSLog(@"BEGAN");//TEST OK
    UITouch* tap=[touches anyObject]; 
    start_point=[tap locationInView:self];
}


-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event 
{
    NSLog(@"MOVED");//TEST OK
    UITouch* tap=[touches anyObject]; 
    current_point=[tap locationInView:self];
    [self DrawLine:start_point end:current_point];
    start_point=current_point;
} 


-(void)DrawLine: (CGPoint)start end:(CGPoint)end 
{
    context= UIGraphicsGetCurrentContext();
    CGColorSpaceRef space_color= CGColorSpaceCreateDeviceRGB(); 
    CGFloat component[]={1.0,0.0,0.0,1};
    CGColorRef color = CGColorCreate(space_color, component);

    //draw line 
    CGContextSetLineWidth(context, 1);
    CGContextSetStrokeColorWithColor(context, color);
    CGContextMoveToPoint(context, start.x, start.y);
    CGContextAddLineToPoint(context,end.x, end.y);
    CGContextStrokePath(context);
}

我的问题是当我在屏幕上画线但是线条不可见时。

P.S我在主要的应用视图上绘制

2 个答案:

答案 0 :(得分:3)

context= UIGraphicsGetCurrentContext();

您从UIGraphicsGetCurrentContext()方法之外调用drawRect:。所以它会返回nil。因此,以下函数尝试绘制实际上nil的上下文,这显然无法正常工作

答案 1 :(得分:0)

正如@Jorg所提到的,drawRect:方法之外没有当前上下文,因此UIGraphicsGetCurrentContext()最有可能返回nil

您可以使用CGLayerRef在屏幕外绘图,而在drawRect:方法中,您可以在视图上绘制图层的内容。

首先,您需要将图层声明为您的类的成员,因此在@interface声明CGLayerRef _offscreenLayer;中。您也可以为它创建一个属性,但是,我将在此示例中直接使用它。

你的init方法中的某个地方:

CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(NULL, self.frame.size.width, self.frame.size.height, 8, 4 * self.frame.size.width, colorspace, (uint32_t)kCGImageAlphaPremultipliedFirst);
CGColorSpaceRelease(colorspace);
_offscreenLayer = CGLayerCreateWithContext(context, self.frame.size, NULL);

现在,我们来处理绘图:

-(void)DrawLine: (CGPoint)start end:(CGPoint)end 
{
    CGContextRef context = CGLayerGetContext(_offscreenLayer);
    // ** draw your line using context defined above
    [self setNeedsDisplay]; // or even better, use setNeedsDisplayInRect:, and compute the dirty rect using start and end points
}
-(void)drawRect:(CGRect)rect {
    CGContextRef currentContext = UIGraphicsGetCurrentContext(); // this will work now, since we're in drawRect:
    CGRect drawRect = CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height);
    CGContextDrawLayerInRect(currentContext, drawRect, _offscreenLayer);
}

请注意,您可能需要进行少量更改才能使代码正常工作,但应该让您了解如何实现它。

相关问题