Yes, I fix this problem, and UIImage is correct, but actually I still get the nil data to create MTLTexture. But When I load a png file, everything is ok
This is my test code:
self.device = MTLCreateSystemDefaultDevice();
// My Text Image
CIFilter<CITextImageGenerator> * filter = [CIFilter textImageGeneratorFilter];
filter.text = @"This is a test text";
filter.fontName = @"HoeflerText-Regular";
filter.fontSize = 12;
filter.scaleFactor = 1.0;
CIImage *image = filter.outputImage;
CIContext *cicontext = [CIContext contextWithOptions:nil];
CGImageRef resultRef = [cicontext createCGImage:image fromRect:image.extent];
UIImage *resultImage = [UIImage imageWithCGImage:resultRef];
// PNG Image
// UIImage *resultImage = [UIImage imageNamed:@"nx"];
// CGImageRef resultRef = resultImage.CGImage;
CFDataRef data = CGDataProviderCopyData(CGImageGetDataProvider(resultRef));
const unsigned char * buffer = CFDataGetBytePtr(data);
CGFloat width = CGImageGetWidth(resultRef), height = CGImageGetHeight(resultRef);
NSInteger bytesPerPixel = 4, bytesPerRow = bytesPerPixel * width, bitsPerComponent = 8;
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
void *rawData = calloc(height * width * bytesPerPixel, sizeof(uint8_t));
if (rawData == nil) {
CGColorSpaceRelease(colorSpace);
colorSpace = NULL;
}
CGContextRef context = CGBitmapContextCreate(rawData, width, height, bitsPerComponent, bytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast|kCGImageByteOrder32Big);
CGColorSpaceRelease(colorSpace);
colorSpace = NULL;
if (context == nil) {
free(rawData);
}
CGContextTranslateCTM(context, 0, height);
CGContextScaleCTM(context, 1, -1);
CGContextDrawImage(context, CGRectMake(0, 0, width, height), resultRef);
MTLTextureDescriptor *textureDescriptor = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA8Unorm width:width height:height mipmapped:NO];
id<MTLTexture> texture = [self.device newTextureWithDescriptor:textureDescriptor];
if (!texture) {
free(rawData);
CGContextRelease(context);
}
MTLRegion region = MTLRegionMake3D(0, 0, 0, width, height, 1);
[texture replaceRegion:region mipmapLevel:0 withBytes:rawData bytesPerRow:bytesPerRow];
free(rawData);
CGContextRelease(context);
_fontTexture = texture;
Thank you very much!
Post
Replies
Boosts
Views
Activity
This is my test image named nx