iOS 文字轉化成圖片

來源:互聯網
上載者:User

標籤:

 

//文字轉化成圖片

-(UIImage *)imageFromText:(NSArray*)arrContent withFont:(CGFloat)fontSize withTextColor:(UIColor *)textColor withBgImage:(UIImage *)bgImage withBgColor:(UIColor *)bgColor

{

    // set the font type and size

    

    UIFont *font = [UIFont fontWithName:@"Heiti SC" size:fontSize];

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

    

    CGFloat fHeight = 0.0f;

    for (NSString *sContent in arrContent) {

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

        [arrHeight addObject:[NSNumber numberWithFloat:stringSize.height]];

        

        fHeight += stringSize.height;

    }

    

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

    

    // Create a stretchable image for the top of the background and draw it

    UIGraphicsBeginImageContextWithOptions(newSize,NO,0.0);

    CGContextRef ctx = UIGraphicsGetCurrentContext();

    

    //如果設定了背景圖片

    if(bgImage)

    {

        UIImage* stretchedTopImage = [bgImage stretchableImageWithLeftCapWidth:0 topCapHeight:0];

        [stretchedTopImage drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];

    }else

    {

        if(bgColor)

        {

            //填充背景顏色

            [bgColor set];

            UIRectFill(CGRectMake(0, 0, newSize.width, newSize.height));

        }

    }

    

    CGContextSetCharacterSpacing(ctx, 10);

    CGContextSetTextDrawingMode (ctx, kCGTextFillClip);

    [textColor set];

    

    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:NSLineBreakByWordWrapping alignment:NSTextAlignmentLeft];

        

        fPosY += [numHeight floatValue];

        nIndex++;

    }

    

    // transfer image

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    

    return image;

    

}

 

iOS 文字轉化成圖片

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.