2017-08-09 7 views
0

J'ai trouvé ce code qui devrait dessiner un texte en utilisant un UIFont. Je voudrais obtenir un UIImage de cela pour s'assurer que cela fonctionne.iOS - Obtenir UIImage à partir de CGBitmapContext

-je obtenir une texture OpenGL plus tard pour mes besoins, mais depuis sa ne pas montrer tout ce que je préfère vérifier le code fonctionne:

NSUInteger width, height, i; 
CGContextRef context; 
void *data; 
CGColorSpaceRef colorSpace; 
UIFont *font; 

font = [UIFont fontWithName:name size:size]; 

width = (NSUInteger)dimensions.width; 
if ((width != 1) && (width & (width - 1))) { 
    i = 1; 
    while (i < width) 
     i *= 2; 
    width = i; 
} 
height = (NSUInteger)dimensions.height; 
if ((height != 1) && (height & (height - 1))) { 
    i = 1; 
    while (i < height) 
     i *= 2; 
    height = i; 
} 

colorSpace = CGColorSpaceCreateDeviceGray(); 
data = calloc(height, width); 
context = CGBitmapContextCreate(data, width, height, 8, width, colorSpace, kCGImageAlphaNone); 

CGColorSpaceRelease(colorSpace); 

CGContextSetGrayFillColor(context, 1.0, 1.0); 
CGContextTranslateCTM(context, 0.0, height); 
CGContextScaleCTM(context, 1.0f, -1.0f); //NOTE: NSString draws in UIKit referential i.e. renders upside-down compared to CGBitmapContext referential 
UIGraphicsPushContext(context); 

NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy]; 
[style setLineBreakMode:NSLineBreakByWordWrapping]; 

NSDictionary *attrsDictionary = @{ 
            NSFontAttributeName: font, 
            NSBaselineOffsetAttributeName: @1.0F, 
            NSParagraphStyleAttributeName: style 
            }; 

[string drawInRect:CGRectMake(0, 0, dimensions.width, dimensions.height) 
    withAttributes:attrsDictionary]; 

UIGraphicsPopContext(); 

// Here I use "void *data" to obtain an OpenGL texture 
// ... 
// ... 

CGContextRelease(context); 
free(data); 

Merci beaucoup à l'avance, toute aide serait appréciée!

Répondre

0

trouvé la solution:

CGImageRef cgImageFinal = CGBitmapContextCreateImage(context); 
UIImage *newImage = [[UIImage alloc]initWithCGImage:cgImageFinal]; 

De plus, je devais définir la couleur du texte en blanc:

UIColor *whiteColor = [UIColor whiteColor]; 
NSDictionary *attrsDictionary = @{ 
            NSFontAttributeName: font, 
            NSBaselineOffsetAttributeName: @1.0F, 
            NSParagraphStyleAttributeName: style, 
            NSForegroundColorAttributeName: whiteColor 
            };