自定义UIView以实现自绘

本文介绍如何通过自定义UIview来绘制简单的图形,包括曲线、三角形、矩形和圆形等,适用于iOS应用中需要定制化显示图形的场景。

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

有时候我们需要自绘uiview以实现自己的需求,比如根据坐标点绘制出连续的曲线(股票走势图),就需要自绘uiview了。

原理:继承uiview类(customView),并实现custom view的drawRect即可。

首先看一下效果图:


代码如下:

// .h

#import <UIKit/UIKit.h>


@interface CustomView : UIView

@end


//.m

#import "CustomView.h"


@implementation CustomView


-(id)initWithFrame:(CGRect)frame{

    //重写initWithFrame时,不要忘了下面一句

    self = [superinitWithFrame:frame];

    

    if (self) {

        self.backgroundColor = [UIColorwhiteColor];

    }

    

    return self;

}


//重写drawRect方法(不需要调用),绘制想要的图像

-(void)drawRect:(CGRect)rect{

 

    CGContextRef context = UIGraphicsGetCurrentContext();//context:一块内存区域,将它看做当前view的画布就行了。


    NSDictionary *attribute = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize: 15.0f], NSFontAttributeName, [UIColor redColor],  NSForegroundColorAttributeName, nil];

    [@"股市走势图" drawInRect:CGRectMake(100, 200, 80, 20) withAttributes:attribute] ;//绘画标题

    

    //曲线

    CGContextMoveToPoint(context, 10, 400);

    CGContextAddLineToPoint(context, 100, 450);

    CGContextAddLineToPoint(context, 150, 400);

    CGContextAddLineToPoint(context, 200, 450);

    //CGContextStrokePath(context);

    

    //三角形

    CGContextMoveToPoint(context, 20, 100);

    CGContextAddLineToPoint(context, 40, 300);

    CGContextAddLineToPoint(context, 200, 200);

    CGContextClosePath(context);

    CGContextStrokePath(context);

    //CGContextFillPath(context);

    

    //矩形

    CGContextAddRect(context, CGRectMake(20, 20, 100, 50));

    [[UIColor colorWithRed:1 green:0 blue:0 alpha:1] set];

    //CGContextStrokePath(context);//空心

    CGContextFillPath(context);//实心

    

     //

    CGContextAddArc(context, 150, 150, 100, 0, 2*M_PI, 0);

    CGContextStrokePath(context);

}


@end


然后在需要用到该view的view controller的

viewDidLoad下添加西;下面代码就可以了!

CustomView *view = [[CustomView alloc]  initWithFrame:[UIScreen mainScreen].bounds];

[self.view addSubview view];


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值