开发者

How do I determine the location of each pixel in a square drawn via Core Graphics?

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);
    CGContext开发者_运维知识库StrokePath(ctx);
    CGContextRestoreGState(ctx);

    CGContextRestoreGState(ctx);
    [self setNeedsDisplay];
    CGPathRelease(path);
}


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.


I needed to do something similar for my iPhone app and while I realize it is a little late, I decided to respond anyway.

First, initialize a mutable array (points).

Next, find the minimum X and Y coordinates for your CGRect. Do the same for the maximum.

Find the difference between the minimum and the maximum.

Now, create a for loop like the one below:

for(int x = minX; x<diffX+minX; x++){
    for(int y = minY; y<diffY+minY; y++){
        [points addObject:[NSValue valueWithCGPoint:CGPointMake(x,y)]];
    }
}

You can now access your points through the points array.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜