質問

I'm trying to implement freehand drawing on top of an image, but I don't want to save the result as an image. I've adapted code from this article, but I am not seeing anything draw (though I know the drawRect method is being called). I've verified that I'm iterating through valid CGPoints in the for loop. So everything seems in line, but nothing is physically being drawn.

Am I missing something?

Also, just to note, I've stripped the shape drawing section out, but that is working (drawing ovals, rectangles, and lines).

Here's the code:

- (void)drawRect:(CGRect)rect
{
    if( self.shapeType == DrawShapeTypeCustom )
    {
        if( !self.myDrawings )
        {
            self.myDrawings = [[NSMutableArray alloc] initWithCapacity:0];
        }

        CGContextRef ctx = UIGraphicsGetCurrentContext();
        CGFloat red = 0.0, green = 0.0, blue = 0.0, alpha =0.0;
        [[UIColor redColor] getRed:&red green:&green blue:&blue alpha:&alpha];

        CGContextSetRGBFillColor( ctx , red , green , blue , 0.0 );
        CGContextSetRGBStrokeColor( ctx , red , green , blue , 0.9 );

        CGContextSetLineWidth( ctx , (CGFloat) 5 );

        if( [self.myDrawings count] > 0 )
        {
            CGContextSetLineWidth(ctx , 5);

            for( int i = 0 ; i < [self.myDrawings count] ; i++ )
            {
                NSArray * array = [self.myDrawings objectAtIndex:i];

                if( [array count] > 2 )
                {
                    CGFloat x = [[array objectAtIndex:0] floatValue];
                    CGFloat y = [[array objectAtIndex:1] floatValue];

                    CGContextBeginPath( ctx );
                    CGContextMoveToPoint( ctx , x, y);
                    for( int j = 2 ; j < [array count] ; j+= 2 )
                    {
                        x = [[array objectAtIndex:0] floatValue];
                        y = [[array objectAtIndex:1] floatValue];

                        CGContextAddLineToPoint( ctx , x , y );
                    }
                }

                CGContextStrokePath( ctx );
            }

        }
    }
    else
    {
        // Draw shapes...
    }
}
役に立ちましたか?

解決

for( int j = 2 ; j < [array count] ; j+= 2 )
{
    x = [[array objectAtIndex:0] floatValue];
    y = [[array objectAtIndex:1] floatValue];

    CGContextAddLineToPoint( ctx , x , y );
}

It looks like you are drawing to the same point over and over again. I guess you should actually use the value of j you're looping through.

for( int j = 2 ; j < [array count] ; j+= 2 )
{
    x = [[array objectAtIndex:j + 0] floatValue];
    y = [[array objectAtIndex:j + 1] floatValue];

    CGContextAddLineToPoint( ctx , x , y );
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top