views:

131

answers:

1

Hi, I am trying to get each pixel point of a Square drawn using Core graphics.Here by making the stroke color black color,I am drawing the Square.Please give me an idea how I will get all pixel point on which this square is drawn.

- (void)drawRect:(CGRect)rect 
{
    CGMutablePathRef path = CGPathCreateMutable(); 
    CGContextRef ctx = UIGraphicsGetCurrentContext();

    CGPathMoveToPoint(path, NULL, 30.0f, 30.0f);
    CGPathAddLineToPoint(path, NULL, 130.0f, 30.0f);
    CGPathAddLineToPoint(path, NULL, 130.0f, 130.0f);
    CGPathAddLineToPoint(path, NULL, 30.0f, 130.0f);
    CGPathCloseSubpath(path);
    CGPathRetain(path);
    CGContextSetFillColorWithColor(ctx, [UIColor clearColor].CGColor); 
    CGContextSetStrokeColorWithColor(ctx,[UIColor blackColor].CGColor);
    CGContextSetLineWidth(ctx, 2.0);
    CGContextSaveGState(ctx);
    CGContextAddPath(ctx, path); 

    CGContextRestoreGState(ctx);
    CGContextStrokePath(ctx);
    CGContextRestoreGState(ctx);

    CGContextRestoreGState(ctx);
    [self setNeedsDisplay];
    CGPathRelease(path);
}
+5  A: 

Why are you doing all this work instead of just using CGContextFillRect() and CGContextStrokeRect()?

Your code above can be simplified to:

CGRect r = CGRectMake(30.0, 30.0, 100.0, 100.0);
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(ctx, CGColorGetConstantColor(kCGColorClear));
CGContextFillRect(ctx, r);
CGContextSetLineWidth(ctx, 2.0);
CGContextSetStrokeColorWithColor(ctx, CGColorGetConstantColor(kCGColorBlack));
CGContextStrokeRect(ctx, r);

Also, never send -setNeedsDisplay within your -drawRect: method. You'll get an infinite loop.

NSResponder