我正在尝试从NSAttributedString创建一个具有偏斜变换的UIImage。我可以制作一个UILabel或UIImageView并使该视图偏斜,但不幸的是我需要在字符串偏斜后创建一个UIImage。我试过以下......
CGAffineTransform skewTransform = CGAffineTransformIdentity;
skewTransform.b = (M_1_PI / 2);
UIGraphicsBeginImageContextWithOptions(mSize, NO, 1.0);
UILabel* skewedLabel = [[UILabel alloc] init];
skewedLabel.attributedText = stringToBeSkewed;
CGContextSetTextMatrix(UIGraphicsGetCurrentContext(), skewTransform);
skewedLabel.layer.affineTransform = skewTransform;
// The following 3 calls haven't worked
// [stringToBeSkewed drawInRect:inputRectParam.rect];
// [skewedLabel.layer renderInContext:UIGraphicsGetCurrentContext()];
// [skewedLabel.layer drawInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
我知道CALayer是CoreAnimation而CoreGraphics不会识别这个,但有没有办法让偏斜的文本在上下文中被捕获并转换成UIImage?
答案 0 :(得分:1)
通过执行以下操作,我能够从文本中获取UIImage,希望这可以帮助某人。此外,它不是最干净的图像,所以任何有关锐化的建议都会受到赞赏。
UIFont* font = [UIFont fontWithName:@"(your font name)" size:60];
CTFontRef skewFont = CTFontCreateWithName((__bridge CFStringRef)font.fontName, font.pointSize, NULL);
// Create an attributed string for shadowed text
CFStringRef skewKeys[] = { kCTFontAttributeName, kCTForegroundColorAttributeName };
CFTypeRef skewValues[] = { skewFont, [UIColor colorWithRed:0 green:0 blue:0 alpha:.4].CGColor };
CFDictionaryRef skewAttributes = CFDictionaryCreate(NULL, (const void **)&skewKeys, (const void **)&skewValues,
sizeof(skewKeys) / sizeof(skewKeys[0]), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
CFStringRef theCFString = (__bridge CFStringRef)inputStringParam.string;
CFAttributedStringRef skewString = CFAttributedStringCreate(NULL, theCFString, skewAttributes);
CFRelease(skewAttributes);
// create skew transform
CGAffineTransform skewTransform = CGAffineTransformIdentity;
skewTransform.b = (value to be skewed);
// Draw the string
CTLineRef skewLine = CTLineCreateWithAttributedString(skewString);
CGContextSetTextMatrix(UIGraphicsGetCurrentContext(), CGAffineTransformMakeScale(1.0, -1.0));
CGContextConcatCTM(UIGraphicsGetCurrentContext(), skewTransform);
// draw and capture shadow image
CGContextSetTextPosition(UIGraphicsGetCurrentContext(), inputDrawPointParam.point.x, inputDrawPointParam.point.y);
CTLineDraw(skewLine, UIGraphicsGetCurrentContext());
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CFRelease(skewLine);
CFRelease(skewString);
CFRelease(skewFont);