如果需要进行自定义UI的开发,需要写一个类继承 UIView或者希望重新实现的其他UI组件,并重写drawRect方法,在这里进行绘图操作,程序会自动调用此方法进行绘图。
如果需要随时重绘UI组件我们可以调用UIView类中的setNeedsDisplay方法,则程序会自动调用drawRect方法进行重绘。
例子一
一、在建立一个新工程,此处建立了一个名为CustomUIViewApp的工程。然后如下图,右键新建一个继承了UIView的文件。
二、如下图,选择文件类型,并输入文件名字以及继承的类。
三、在相应文件输入代码。
CustomView.m
//
// CustomView.m
// CustomUIViewApp
//
// Created by Apple on 16/5/18.
// Copyright © 2016年 Apple. All rights reserved.
//
#import "CustomView.h"
@implementation CustomView
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
// Drawing code
NSLog(@"-----------drawRect-----------");
UIImage* image = [UIImage imageNamed:@"2.jpg"];
[image drawInRect:CGRectMake(0, 0, 50, 50)];
}
@end
ViewController.m
//
// ViewController.m
// CustomUIViewApp
//
// Created by Apple on 16/5/18.
// Copyright © 2016年 Apple. All rights reserved.
//
#import "ViewController.h"
#import "CustomView.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
CustomView* customView = [[CustomView alloc] initWithFrame:CGRectMake(50, 50, 50, 50)];
[self.view addSubview:customView];
}
@end
四、效果图如下:
例子二
类似上面的步骤一二,不过这次建立的工程名字为TCustomViewDemo,建立的自定义组件名字为TCustomView。
TCustomView.m
//
// TCustomView.m
// TCustomViewDemo
//
// Created by Apple on 16/5/18.
// Copyright © 2016年 Apple. All rights reserved.
//
#import "TCustomView.h"
@implementation TCustomView
// 定义两个变量记录当前触碰点的坐标
int curX;
int curY;
- (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
// 获取触碰事件的UITouch事件
UITouch*touch = [touches anyObject];
// 得到触碰事件在当前组件上的触碰点
CGPoint lastTouch = [touch locationInView:self];
// 获取触碰点的坐标
curX =lastTouch.x;
curY =lastTouch.y;
// 通知该组件重绘
[self setNeedsDisplay];
}
// 重写该方法来绘制该UI控件
- (void)drawRect:(CGRect)rect
{
// 获取绘图上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();
// 设置填充颜色
CGContextSetFillColorWithColor(ctx,[[UIColor redColor] CGColor]);
// 以触碰点为圆心,绘制一个圆形
CGContextFillEllipseInRect(ctx,CGRectMake(curX - 10, curY - 10, 20, 20));
}
@end
ViewController.m
//
// ViewController.m
// TCustomViewDemo
//
// Created by Apple on 16/5/18.
// Copyright © 2016年 Apple. All rights reserved.
//
#import "ViewController.h"
#import "TCustomView.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
CGRect rect = self.view.frame;
TCustomView* tcustomView = [[TCustomView alloc] initWithFrame:CGRectMake(0, 20, rect.size.width, rect.size.height)];
[self.view addSubview:tcustomView];
}
@end
运行程序后,在虚拟机屏幕上,按住鼠标左键,不断滑动,可以看到以下效果图: