ios 仿某d的头像画圆

今天学习某app,用名字做头像,画圆,里面写字

一开始,打算做头像是image格式。所以就:

   CGRect rect = CGRectMake(0.0f, 0.0f, size.width, size.height);

    UIGraphicsBeginImageContext(rect.size);

    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetFillColorWithColor(context, [color CGColor]);

    CGContextFillEllipseInRect(context, rect);

     //写字

    CGContextSetLineWidth(context, 1.0);

    CGContextSetRGBFillColor (context, 0, 0, 0, 1);

    UIFont  *font = [UIFont boldSystemFontOfSize:12.0];

 

  NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];

 

    paragraphStyle.alignment = NSTextAlignmentCenter;//设置居中

 

    NSDictionary *attributes = @{NSFontAttributeName: font,

 

                                 NSParagraphStyleAttributeName:paragraphStyle ,

 

                                 NSForegroundColorAttributeName:[UIColor whiteColor]};

 

    [sting drawInRect:CGRectMake(0, 10, 34, 18) withAttributes:attributes];

 

    [sting drawInRect:CGRectMake(3.5, 7.5, 25, 15) withFont:font];

 

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return image;

但是返回的圈圈不平滑,有锯齿。蛋疼。。

然后,就重写view的drawrect方法

- (id)initWithFrame:(CGRect)frame { 

    self = [super initWithFrame:frame];

    if (self) {

        [self setBackgroundColor:[UIColor clearColor]];

    }

    return self;

}

- (void)drawRect:(CGRect)rect

{

    //一个不透明类型的Quartz 2D绘画环境,相当于一个画布,你可以在上面任意绘画

    CGContextRef context = UIGraphicsGetCurrentContext();

    //画圆

    CGContextSetFillColorWithColor(context, self.imgColor.CGColor);

    CGContextFillEllipseInRect(context, rect);

    //写字

    CGContextSetLineWidth(context, 1.0);

    CGContextSetRGBFillColor (context, 0, 0, 0, 1);

    UIFont  *font = [UIFont systemFontOfSize:12.0];

    [self.title drawInRect:CGRectMake(3.5, 8, 25, 15) withFont:font];

}

这个是解决了问题,但是强迫症的我。。。头像不是应该图片吗。。而且,就算不是。。上面那个问题也没有解决。这可不行。。

然后有高手提示我“理解是绘制到image上的土,设置为retain分辨率,而view中获取的context本身就是retain”,

于是,第一个方法中画图的方法,只需要把绿色的地方,换成下面这行代码

UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);

这个方法scale参数最好是设置成[UIScreen mainScreen].scale,为什么呢。。跟系统一致麻。。

好了,希望对大家有用,反正我也是为了自己以后能复用。。

posted @ 2015-03-13 17:26  sognoNL  阅读(400)  评论(0编辑  收藏  举报