1. 程式人生 > >iOS 富文字、圖文混排

iOS 富文字、圖文混排

#import "testView.h"
#import <CoreText/CoreText.h>

@implementation testView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self addSubview:self.imageView];
        self.backgroundColor = [UIColor whiteColor];
    }
    return self;
}

- (void)drawRect:(CGRect)rect {
    [self createStingWithFeature];
}
- (void)createStingWithFeature{
    CTFontRef font =  CTFontCreateWithName(CFSTR("Georgia"), 15, NULL);
    NSMutableAttributedString *string = [[NSMutableAttributedString alloc]initWithString:@"由於圖片寬度是固定的這樣就可以計算每行文字縮短的字數。只要文字的總體高度低於影象總高度則文字長度都是縮短的。用CTTypesetterSuggestLineBreak函式動態的計算每一行裡的字數,因為每一行裡面的中文字、標點符號、數字、字母都不一樣所以可以顯示的字數肯定也是不同的,所以需要作這樣的計算。這樣迴圈直至文字結束,就可以知道有多少行字了。再根據字型高度和行間距得出總的文字高度,如果文字高度大於圖片總高度那麼顯示區域的Frame高度就是文字的高度,反之亦然。"];
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetTextMatrix(context,CGAffineTransformIdentity);//重置
    CGContextTranslateCTM(context,0,30); //y軸高度
    CGContextScaleCTM(context,1.0,-1.0);//y軸翻轉
    float lineHeight = 20;
    BOOL drawFlag = YES;
    
    [string addAttribute:NSFontAttributeName value:(__bridge id)font range:NSMakeRange(0, [string length])];
    CFIndex currentIndex = 0;
    float y = 0;
    CTTypesetterRef type = CTTypesetterCreateWithAttributedString((__bridge CFAttributedStringRef)string);
    CFIndex linelenth = 0;
    while (drawFlag) {
        if ((currentIndex + linelenth ) >= [string length]) {
            drawFlag = NO;
        }
        if (y >= - CGRectGetMaxY(self.imageView.frame) + 20) {
            CGContextSetTextPosition(context, self.imageView.bounds.size.width + 5, y);
             linelenth = CTTypesetterSuggestLineBreak(type, 0, self.bounds.size.width - self.imageView.bounds.size.width);
        }else{
            CGContextSetTextPosition(context, 0, y);
            linelenth = CTTypesetterSuggestLineBreak(type, 0, self.bounds.size.width );
        }
        CFRange range = CFRangeMake(currentIndex, linelenth);
        CTLineRef line = CTTypesetterCreateLine(type, range);
        CTLineDraw(line, context);
        currentIndex = currentIndex + linelenth;
        y = y - lineHeight;
    }
}
- (UIImageView *)imageView{
    if (!_imageView) {
        _imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 20, 200, 200)];
        _imageView.image = [UIImage imageNamed:@"dog123.jpg"];
        
    }
    return _imageView;
}

@end