ios - 如何在图像周围绘制文字

标签 ios objective-c core-text

我必须在iOS 6和iOS 7上进行以下操作:
但是我不知道该怎么做。
你能帮助我吗?

最佳答案

要使用CoreText在图像周围绘制文本,您需要创建一个CTFramesetterRef
然后通过调用CTFrameRef创建一个CTFramesetterCreateFrame,其路径指定框架的形状。

UIView的左上角绘制图像并在图像周围添加一些文本的示例代码:

@implementation MyView
- (void)drawRect:(CGRect)rect
{
    UIImage *image = [UIImage imageNamed:@"YourArrowImage"];

    // create the transform to flip the path and text drawing
    CGAffineTransform transform = CGAffineTransformMakeTranslation(0, rect.size.height);
    transform = CGAffineTransformScale(transform, 1., -1.);

    // create a path that's exclude the image rect { .origin = CGPointZero, .size = [image size] } from the rect
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathMoveToPoint(path, &transform, [image size].width, 0);
    CGPathAddLineToPoint(path, &transform, rect.size.width, 0);
    CGPathAddLineToPoint(path, &transform, rect.size.width, rect.size.height);
    CGPathAddLineToPoint(path, &transform, 0, rect.size.height);
    CGPathAddLineToPoint(path, &transform, 0, [image size].height);
    CGPathAddLineToPoint(path, &transform, [image size].width, [image size].height);
    CGPathCloseSubpath(path);

    // setup your text with the desired attributes
    NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:@"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed non risus."
                                                                           attributes:@{ NSFontAttributeName :[UIFont systemFontOfSize:24.],
                                                       NSForegroundColorAttributeName: [UIColor grayColor] }];

    // create CoreText framesetter and the text frame to draw
    CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)attributedString);

    [attributedString release];

    CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0,0), path, NULL);

    CFRelease(path);
    CFRelease(framesetter);

    CGContextRef ctx = UIGraphicsGetCurrentContext();

    // save graphics state
    CGContextSaveGState(ctx);

    // apply the transfom to draw the text
    CGContextConcatCTM(ctx, transform);
    // draw the text frame
    CTFrameDraw(frame, ctx);

    // restore graphics state
    CGContextRestoreGState(ctx);

    CFRelease(frame);

    // draw the image
    [image drawAtPoint:CGPointMake(0,0)];
}
@end

关于ios - 如何在图像周围绘制文字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22638248/

相关文章:

ios - 当联系人已链接联系人时,ABAddressBookGetPersonWithRecordID 返回 NULL

ios - Core Text - 字形高度

ios - 如何在只有全名的情况下使用姓氏对核心数据进行排序?

ios - 强制从用户设备中删除/失效 iOS 应用程序

objective-c - swift init 不可用。 init 不可用只能由框架内部创建

iphone - 在 iPhone 中将图像、字符串文件添加到静态库

iphone - 来自 CTFontRef 的字体名称

iphone - iPhone 中调用某些 CTFunction 时出现内存泄漏

ios - 我如何使用 Alamofire 进行基于 token 的身份验证?

ios - Cordova 插件 Datepicker 弹出窗口,在 iPad 上显示在错误的位置