iOS.TextKit.02.文字图片混合排版

本文介绍如何利用TextKit框架实现iOS应用中文本环绕图片的效果。通过创建文本存储对象、布局管理器对象及文本容器对象,并设置它们之间的关系来完成布局。此外,还展示了如何设置文本样式以及实现文本围绕图片的路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、案例如图

2、代码

TextKit02ViewController.h
#import <UIKit/UIKit.h>

@interface TextKit02ViewController : UIViewController

@property (nonatomic,strong) IBOutlet UITextView *textView;

@property (nonatomic,weak) IBOutlet UIImageView *imageView;
// 文本可以排版的区域
@property (nonatomic,strong) NSTextContainer *textContainer;

@end
TextKit02ViewController.m
#import "TextKit02ViewController.h"

@interface TextKit02ViewController ()

@end

@implementation TextKit02ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    CGRect textViewRect = CGRectInset(self.view.bounds, 10.0, 20.0);
    
    // 1、创建储存文本对象textStorage
    NSTextStorage *textStorage = [[NSTextStorage alloc] initWithString:self.textView.text];
    
    // 2、创建文字排版对象layoutManager
    NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
    
    // 3、创建文本排版的区域textContainer
    self.textContainer = [[NSTextContainer alloc] initWithSize:textViewRect.size];
    
    // 4、设置textStorage与layoutManager的关系
    [textStorage addLayoutManager:layoutManager];
    
    // 5、设置layoutManager与textContainer的关系
    [layoutManager addTextContainer:self.textContainer];
    
    // 6、重新构建原来控制器视图
    [self.textView removeFromSuperview];
    self.textView = [[UITextView alloc] initWithFrame:textViewRect textContainer:self.textContainer];
    [self.view insertSubview:self.textView belowSubview:self.imageView];
    
    // 7、设置textStorage中文本的风格
    [textStorage beginEditing];
    
    NSDictionary *attrsDic = @{NSTextEffectAttributeName:NSTextEffectLetterpressStyle};
    NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:self.textView.text attributes:attrsDic];
    [textStorage setAttributedString:attrStr];
    
    [textStorage endEditing];
    
    // 8、环绕路径
    self.textView.textContainer.exclusionPaths = @[[self translatedBezierPath]];
   
}

- (UIBezierPath *)translatedBezierPath
{
    CGRect imageRect = [self.textView convertRect:self.imageView.frame fromView:self.view];
    UIBezierPath *newPath = [UIBezierPath bezierPathWithRect:imageRect];
    return newPath;
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

 

 

转载于:https://www.cnblogs.com/cqchen/p/3776205.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值