zoukankan      html  css  js  c++  java
  • IOS-将长文字转化成图片方法

    我们在看微博时,会看到一些长图片上的显示文章,现在就介绍下如何实现。分析下还是很简单的,总结如下:1、计算文字区域的高 2、利用UIGraphics图形上下文方法来实现 3、验证方法:UIImageWriteToSavedPhotosAlbum,在本地相册中查看成功与否。

    -(UIImage *)imageFromText:(NSArray*) arrContent withFont: (CGFloat)fontSize

    {

        // set the font type and size

        UIFont *font = [UIFontsystemFontOfSize:fontSize];

        NSMutableArray *arrHeight = [[NSMutableArrayalloc] initWithCapacity:arrContent.count];

        

        CGFloat fHeight = 0.0f;

        for (NSString *sContent in arrContent) {

            CGSize stringSize = [sContent sizeWithFont:font constrainedToSize:CGSizeMake(CONTENT_MAX_WIDTH, 10000) lineBreakMode:UILineBreakModeWordWrap];

            [arrHeight addObject:[NSNumbernumberWithFloat:stringSize.height]];

            fHeight += stringSize.height;

        }

        

        CGSize newSize = CGSizeMake(CONTENT_MAX_WIDTH+20, fHeight+50);

        

        UIGraphicsBeginImageContextWithOptions(newSize,NO,0.0);

        CGContextRef ctx = UIGraphicsGetCurrentContext();

        CGContextSetCharacterSpacing(ctx, 10);

        CGContextSetTextDrawingMode (ctx, kCGTextFillStroke);

        CGContextSetRGBFillColor (ctx, 0.1, 0.2, 0.3, 1); // 6

        CGContextSetRGBStrokeColor (ctx, 0, 0, 0, 1);

        

        int nIndex = 0;

        CGFloat fPosY = 20.0f;

        for (NSString *sContent in arrContent) {

            NSNumber *numHeight = [arrHeight objectAtIndex:nIndex];

            CGRect rect = CGRectMake(10, fPosY, CONTENT_MAX_WIDTH , [numHeight floatValue]);

            [sContent drawInRect:rect withFont:font lineBreakMode:UILineBreakModeWordWrapalignment:UITextAlignmentLeft];

            

            fPosY += [numHeight floatValue];

            nIndex++;

        }

        // transfer image

        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

        UIGraphicsEndImageContext();

        UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);

        return image;

        

    }


  • 相关阅读:
    LeetCode
    LeetCode
    LeetCode
    LeetCode
    LeetCode
    LeetCode
    Python, pandas: how to sort dataframe by index// Merge two dataframes by index
    永久修改VS include目录
    <OFFER05> 05_ReplaceSpaces替换空格
    用二叉树进行排序 x (从小到大)
  • 原文地址:https://www.cnblogs.com/riasky/p/3507256.html
Copyright © 2011-2022 走看看