iOS drawRect绘画

本文介绍如何在iOS开发中使用UIView子类实现基本图形绘制,包括直线和填充三角形的画法,并提供了具体的CGContext绘图代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

绘画只在UIView中执行,需要新建UIView的子类

#if0
// 画一条线
- (void)drawRect:(CGRect)rect{
    CGContextRef ref = UIGraphicsGetCurrentContext(); // 拿到当前画板,在这个画板上画就是在视图上画
    CGContextBeginPath(ref); // 开始绘画

    CGContextMoveToPoint(ref, 0, 0); // 画线
    CGContextAddLineToPoint(ref, 300, 300);

    CGFloat redColor[4] = {1.0, 0, 0, 1.0};
    CGContextSetStrokeColor(ref, redColor); // 设置当前画笔的颜色,这两句可以用[[UIColor whiteColor] setStroke]代替;
    CGContextStrokePath(ref); // 对移动的路径画线
}
#endif

#if 1
// 画三角
- (void)drawRect:(CGRect)rect{
    CGContextRef ref = UIGraphicsGetCurrentContext();
    CGContextSetRGBStrokeColor(ref, 0.5, 0.5, 0.5, 1.0);
    CGContextSetLineWidth(ref, 3.0); // 让线条变粗
    CGPoint points[] = { // 设置四个点画三条线让线连起来
        CGPointMake(100, 100),
        CGPointMake(50, 300),
        CGPointMake(300, 500),
        CGPointMake(100, 100),
    };
    CGContextAddLines(ref, points, sizeof(points) / sizeof(points[0]));
    CGFloat redColor[4] = {1.0, 0, 0, 1.0};   
    CGContextSetFillColor(ref, redColor); // 填充颜色,这两句可使用[[UIColor redColor] setFill];
    CGContextDrawPath(ref, kCGPathFillStroke); // 画填充的图案

}
#endif
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值