Quartz 2D 练习1--触摸简单绘图
总结:
1、单点触摸时,获取坐标:[[touches anyObject] locationInView:self];
2、需要更新图形显示内容时,调用 [self setNeedsDisplay];
3、在绘图事件函数中使用 UIGraphicsGetCurrentContext() 得到画布
4、画线使用 StrokePath
5、绘图前清除旧的显示内容可使用背景色填充视图范围(本例中可以不要)
6、绘图程序一般要支持屏幕自动旋转,在视图控制器的shouldAutorotateToInterfaceOrientation函数中返回YES
TouchesView.h:
#import <UIKit/UIKit.h>
@interface TouchesView : UIView {
CGPoint _startPos;
CGPoint _lastPos;
BOOL _touched;
}
@end
TouchesView.m:
#import "TouchesView.h"
@implementation TouchesView
- (void)dealloc
{
[super dealloc];
}
- (BOOL)isMultipleTouchEnabled
{
return NO;
}
- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, self.backgroundColor.CGColor);
CGContextFillRect(context, self.bounds);
if (_touched) {
if (CGPointEqualToPoint(_startPos, _lastPos)) {
CGContextStrokeEllipseInRect(context,
CGRectMake(_startPos.x - 40, _startPos.y - 40, 80, 80));
} else {
CGContextBeginPath(context);
CGContextMoveToPoint(context, _startPos.x, _startPos.y);
CGContextAddLineToPoint(context, _lastPos.x, _lastPos.y);
CGContextStrokePath(context);
}
}
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
_startPos = [[touches anyObject] locationInView:self];
_lastPos = _startPos;
_touched = YES;
[self setNeedsDisplay];
NSLog(@"touchesBegan: %f,%f", _startPos.x, _startPos.y);
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
_lastPos = [[touches anyObject] locationInView:self];
[self setNeedsDisplay];
NSLog(@"touchesMoved: %f,%f", _lastPos.x, _lastPos.y);
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
_touched = NO;
[self setNeedsDisplay];
}
@end

浙公网安备 33010602011771号