iOS长微博实现

"iOS开发就像搬运工,当搬到一定境界的时候就可以偷懒了"Bison

1
冰之依韩版女装(程序媛福利)

在iOS开发中我们该如何去实现长微博的功能呢?
说白了就是将文字也转成图片的形式来显示
下面请看代码

更多经验请点击

#define CONTENT_MAX_WIDTH   300.0f

+(UIImage *)imageFromText:(NSArray*)arrContent withFont:(CGFloat)fontSize withTextColor:(UIColor *)textColor withBgImage:(UIImage *)bgImage withBgColor:(UIColor *)bgColor
{
// 设置字体类型和大小

    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);


    // 创建一个可拉伸的图像的背景上画
    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, kCGTextFill);
        [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++;
    }

    // 传递图像
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return image;

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值