zoukankan      html  css  js  c++  java
  • 生成带文本的UIImage


    -(UIImage *)createTextImg:(NSString *)imgName text:(NSString *)text1{
        
        UIImage* img = [UIImage imageNamed:imgName];
        NSAssert(img, @"");
        int w = img.size.width;
        int h = img.size.height;
        
        float scale = img.scale;
        w *= scale;
        h *= scale;
        
        // 画图
        CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
        CGContextRef context = CGBitmapContextCreate(NULL, w, h, 8, 4 * w, colorSpace, kCGImageAlphaPremultipliedFirst);
        CGContextDrawImage(context, CGRectMake(0, 0, w, h), img.CGImage);
        
        // 画文本
        CTFontRef ctfont = CTFontCreateWithName(CFSTR("ArialMT"), 16 * scale, NULL);
        CGColorRef ctColor = [[UIColor whiteColor] CGColor];
        
        CFStringRef keys[] = { kCTFontAttributeName,kCTForegroundColorAttributeName };
        CFTypeRef values[] = { ctfont,ctColor};
        CFDictionaryRef attr = CFDictionaryCreate(NULL, (const void **)&keys, (const void **)&values,
                                                  sizeof(keys) / sizeof(keys[0]), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
        
        
        CFStringRef ctStr = CFStringCreateWithCString(nil, [text1 UTF8String], kCFStringEncodingUTF8);
        CFAttributedStringRef attrString = CFAttributedStringCreate(NULL,ctStr, attr);
        CTLineRef line = CTLineCreateWithAttributedString(attrString);
        CGContextSetTextMatrix(context, CGAffineTransformIdentity);
        CGContextSetTextPosition(context, 4 * scale, 22 * scale);
        CTLineDraw(line, context);
        
        CFRelease(line);
        CFRelease(attrString);
        CFRelease(ctStr);
        
        CGImageRef imageMasked = CGBitmapContextCreateImage(context);
        
        CGContextRelease(context);
        CGColorSpaceRelease(colorSpace);
        UIImage *image =[UIImage imageWithCGImage:imageMasked scale:scale orientation:img.imageOrientation];
        CFRelease(imageMasked);
        return image;
    }


  • 相关阅读:
    Unity之串口通信(基于三姿态传感器)
    Unity3d win7协议多点触控
    大大的蛋项目 第二篇 第三关
    大大的蛋项目
    Unity3d 调用C++的DLL
    有梦想的小鸟
    【Unity3D插件】NGUI屏幕自适应 .
    【Unity3d】使GUI适应屏幕分辨率
    unity自动保存项目
    BloomFilter——大规模数据处理利器
  • 原文地址:https://www.cnblogs.com/iapp/p/3631661.html
Copyright © 2011-2022 走看看