文本不会显示在外部位图/jpeg 文件中。绘制点在当前上下文中不起作用?



对CoreGraphics相当陌生,但掌握了基础知识。试图写入外部文件(不是手机屏幕)。所有网格都出现了,但它不会使用drawpoint渲染文本。不管我怎么试,都不管用!

这是我的代码,它触发viewDidLoad:

- (void)viewDidLoad {
    CGFloat width = 312;
    CGFloat height = 482;
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    size_t bitsPerComponent = 8;
    size_t bytesPerPixel    = 4;
    size_t bytesPerRow      = (width * bitsPerComponent * bytesPerPixel + 7) / 8;
    size_t dataSize         = bytesPerRow * height;
    unsigned char *data = malloc(dataSize);
    memset(data, 0, dataSize);
    CGContextRef context = CGBitmapContextCreate(data, width, height, 
                                                 bitsPerComponent, 
                                                 bytesPerRow, colorSpace, 
                                                 kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
    // Flip coordinate system
    CGRect bounds = CGContextGetClipBoundingBox(context);
    CGContextScaleCTM(context, 1.0, -1.0);
    CGContextTranslateCTM(context, 0.0, -bounds.size.height);
    //  And now the magic happens...
    CGContextSetRGBFillColor(context, 1.0, 1.0, 1.0, 1.0);
    CGContextFillRect(context, CGRectMake(0,0,312,482));
    int tableTop=54;
    int cellsPerColumn=26;
    int cellHeight=15;
    [@"Title" drawAtPoint:CGPointMake(8, 8) withFont:[UIFont boldSystemFontOfSize:9.0f]];   //  Doesn't print text on  screen?!
    for(int a=1;a<cellsPerColumn+1;a++)
    {
        CGContextStrokeRect(context, CGRectMake(8,(tableTop+cellHeight*(a+1)),60,cellHeight));
        CGContextStrokeRect(context, CGRectMake(66,(tableTop+cellHeight*(a+1)),85,cellHeight));
        CGContextStrokeRect(context, CGRectMake(159,(tableTop+cellHeight*(a+1)),60,cellHeight));
        CGContextStrokeRect(context, CGRectMake(217,(tableTop+cellHeight*(a+1)),85,cellHeight));
    }

    //  Wrap up context and produce the image...

    CGColorSpaceRelease(colorSpace);
    CGImageRef imageRef = CGBitmapContextCreateImage(context);
    UIImage *result = [[UIImage imageWithCGImage:imageRef] retain];
    CGImageRelease(imageRef);
    CGContextRelease(context);
    free(data);
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"user_images/myImage.jpg"];
    NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(result)];
    [imageData writeToFile:filePath atomically:YES];
    [super viewDidLoad];
}

我在这个上面扯我的头发,它有一些关于设置渲染文本的上下文的东西或者像那样简单的东西。任何帮助,非常感谢!

谢谢,丰富的

实用程序方法,例如drawAtPoint:将只用于在当前图形上下文中绘图,通常是在子类NSView的drawRect回调期间提供的上下文。或者你可以尝试使用setCurrentContext:方法来处理你创建的位图上下文

最新更新