iOS开发精华专题UI控件的一些属性iOS开发技能

iOS开发一行代码解决绘制图片头像(将UILabel/UIVie

2016-07-27  本文已影响1242人  Courage_SC

粉色的小强头像为示例:

1869333-9fb97a258a82e83c.jpg

1、绘制将要转化成图片的UI
HeadImageView.h

#import <UIKit/UIKit.h>

@interface HeadImageView : UIView

- (id)initWithFrame:(CGRect)frame BackGroundColor:(UIColor*)backGroundColor Text:(NSString*)text TextColor:(UIColor*)textColor TextFontOfSize:(CGFloat)size;
@end

HeadImageView.m

#import "HeadImageView.h"

@implementation HeadImageView
- (id)initWithFrame:(CGRect)frame BackGroundColor:(UIColor *)backGroundColor Text:(NSString *)text TextColor:(UIColor *)textColor TextFontOfSize:(CGFloat)size{
    self = [super initWithFrame:frame];
    if (self) {
        UIView *backView = [[UIView alloc] initWithFrame:frame];
        backView.backgroundColor = backGroundColor;
        [self addSubview:backView];
        
        UILabel *label = [[UILabel alloc] initWithFrame:frame];
        label.text = text;
        label.textColor = textColor;
        label.backgroundColor = backGroundColor;
        label.textAlignment = 1;
        label.font = [UIFont systemFontOfSize:size];
        [backView addSubview:label];
    }
    return self;
}
@end

2、建一个类目文件将UI转化成图片Image
HeadImage.m

#import <Foundation/Foundation.h>
#import "HeadImageView.h"

@interface HeadImage : NSObject
+ (UIImage*)imageWithFrame:(CGRect)frame BackGroundColor:(UIColor*)backGroundColor Text:(NSString*)text TextColor:(UIColor*)textColor TextFontOfSize:(CGFloat)size;
@end

HeadImage.h

#import "HeadImage.h"

@implementation HeadImage
+ (UIImage *)imageWithFrame:(CGRect)frame BackGroundColor:(UIColor *)backGroundColor Text:(NSString *)text TextColor:(UIColor *)textColor TextFontOfSize:(CGFloat)size{
//初始化并绘制UI
    HeadImageView *view = [[HeadImageView alloc] initWithFrame:frame BackGroundColor:backGroundColor Text:text TextColor:textColor TextFontOfSize:size];

//转化成image
    UIGraphicsBeginImageContext(view.bounds.size);
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    [view.layer renderInContext:ctx];
    UIImage* tImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return tImage;
}
@end

3、使用方法

//生成图片Image(封装好(背景颜色、图片大小、字体大小、颜色等),一行代码解决绘制图片头像)
UIImage *image = [HeadImage imageWithFrame:CGRectMake(0, 0, 125 * 2 * FitWidth, 125 * 2 * FitHeight) BackGroundColor:[UIColor colorWithRed:0.58 green:0.65 blue:0.81 alpha:1.00] Text:_member.name TextColor:[UIColor whiteColor] TextFontOfSize:30 * 2];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 125 * FitHeight, 125 * FitHeight)];
           imageView.image = image;
           [self.view addSubview:imageView];
上一篇下一篇

猜你喜欢

热点阅读