【发布时间】:2026-01-20 05:25:01
【问题描述】:
CoreGraphics 相当新,但掌握了基础知识。尝试写入外部文件(不是手机屏幕)。所有网格都会出现,但不会使用 drawAtPoint 呈现文本。无论我尝试什么都做不到!
这是我在 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];
}
我在这个问题上大发雷霆,它需要设置用于渲染文本的上下文或类似的简单内容。非常感谢任何帮助!
谢谢, 丰富
【问题讨论】:
标签: ios text core-graphics