drawRect绘图

来源:互联网 发布:网络推广策划案怎么写 编辑:程序博客网 时间:2024/06/05 06:27

在Java的Swing开发中,常用Graphics2D来绘图,虽然用代码的方式来绘图会比较繁琐,但是貌似有很多攻城狮都乐在其中。

iOS里的Core Graphics框架作为一个绘图框架,也提供了很多手动绘图的常用方法。

UIView的drawRect就像是Java中的paintComponent重绘方法:

1.开始要获取一个指向当前上下文的指针(CGContextRef)

- (void)drawRect:(CGRect)rect{      CGContextRef cr = UIGraphicsGetCurrentContext();}

2.然后就可以开始绘制了,比如我想画一个圆,初始的数据需要这些

//先是根据调用者的位置计算中心点CGRect bounds = [self bounds];CGPoint center;center.x = bounds.origin.x + bounds.size.width / 2.0;center.y = bounds.origin.y + bounds.size.height / 2.0;//然后可以根据rect大小计算圆半径 使其充满圆float maxRadius = hypot(bounds.size.width, bounds.size.height) / 4.0;

3.利用上下文开始画圆的路径

//设置线条宽度CGContextSetLineWidth(cr, 15);//设置线条颜色[[UIColor redColor] setStroke];//把参数加入到上下文CGContextAddArc(cr, center.x, center.y, maxRadius, 0.0, M_PI * 2.0, YES);//执行绘图,绘图后把路径移除CGContextStrokePath(cr);

4.最后想往图中写字,并给字体设置阴影偏移

    NSString *text = @"My name is RannieR";        UIFont *font = [UIFont boldSystemFontOfSize:28];        CGRect textRect;    textRect.size = [text sizeWithFont:font];        textRect.origin.x = center.x - textRect.size.width / 2.0 ;    textRect.origin.y = center.y - textRect.size.height / 2.0 ;        [[UIColor blackColor] setFill];        CGSize offset = CGSizeMake(4, 3);        CGColorRef color = [[UIColor grayColor] CGColor];        //第三个参数是 模糊效果参数    CGContextSetShadowWithColor(cr, offset, 2.0, color);        [text drawInRect:textRect withFont:font];





    


原创粉丝点击