drawRect绘图

在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];





    


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值