如何获取使用Core Graphics绘制的空心字符的每个像素位置(坐标)?

时间:2010-01-14 06:01:10

标签: iphone cocoa-touch core-graphics

我使用UIView子类使用Core Graphics绘制字母。使用此代码只有空心字符是drwan(通过使笔画颜色为黑色)。这里我需要角色的每个像素(坐标)位置。请给出我知道如何获得空心角色的每个像素点(只有黑点的像素值)。

源代码:

/*UIView Subclass Method*/

- (void)drawRect:(CGRect)rect
{
      //Method to draw the alphabet
      [self drawChar:@"A" xcoord:5 ycoords:35];
}
-(void)drawChar:(NSString *)str xcoord: (CGFloat)x ycoord: (CGFloat)y
{

    const char *text = [str UTF8String];//Getting the alphabet
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGContextSelectFont(ctx, "Helvetica", 40.0, kCGEncodingMacRoman);
    CGContextSetTextDrawingMode(ctx, kCGTextFillStroke);
    CGContextSetStrokeColorWithColor(ctx, [UIColor blackColor].CGColor);//to make the character hollow-Need only these points
    CGContextSetFillColorWithColor(ctx, [UIColor clearColor].CGColor);//Fill color of character is clear color

    CGAffineTransform xform = CGAffineTransformMake(
                                                    1.0,  0.0,
                                                    0.0, -1.0,
                                                    0.0,  0.0);//Giving a transformation to the alphabet

    CGContextSetTextMatrix(ctx, xform);

   CGContextShowTextAtPoint(ctx, x, y, text, strlen(text));//Generating the character
}

1 个答案:

答案 0 :(得分:2)

首先,有方便的方法来设置填充和描边颜色:

[[UIColor blackColor] setStroke];
[[UIColor clearColor] setFill];

或使用CGContextSetGrayFillColorCGContextSetGrayStrokeColor


至于您的问题,要获取像素信息,您必须使用CGBitmapContext。您可以按CGBitmapContextGetData获取位图。假设您声明了一个RGBA位图,位图数据将排列为

RGBA_at_(0,0)  RGBA_at_(1,0)  ...  RGBA_at_(w,0)  RGBA_at(0,1)  RGBA_at_(1,1) ...

因此,您可以线性扫描任何目标颜色值并确定黑色像素。


请注意,UIGraphicsGetCurrentContext()不一定是CGBitmapContext,因此不应对其应用CGBitmapContextGetData。相反,您必须使用CGBitmapContextCreate创建自己的位图上下文,将文本绘制到此位图上下文中,通过CGBitmapContextCreateImage获取CGImage结果,最后将此CGImage绘制到UIContext上。