標籤:
今天學習某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];
[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,為什麼呢。。跟系統一致麻。。
好了,希望對大家有用,反正我也是為了自己以後能複用。。
ios 仿某d的頭像畫圓