UITouch(包括视图移动的实现)

UITouch对象描绘了手指在屏幕上的移动和交互行为的详细事件。你使用使用UITouch对象把UIEvent对象传递到响应对象中来为事件控制服务。
一个UITouch对象包含了方法可直接用来获取视图或者窗口中发生的触摸事件的位置然後传递到视图或者窗口中去。即可知道什么时候发生了触摸事件,用户触摸了一次还是多次,手指是否是滑过(如果是,会判断哪个方向),以及触摸的开始,移动,或者该动作已结束或者动作是否已取消。
其中,UIView中最常用的四个方法为:

//触摸事件开始是执行的方法, touchs参数为手势的集合, event则为事件

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    NSLog(@"%s",__func__);//输出方法名

    UITouch * touch = [touchesanyObject];

    _beginPoint = [touchlocationInView:self];记录触摸开始发生时的触摸点坐标(坐标相对于自身的View)

}

//触摸事件为移动时会调用的方法

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {

    NSLog(@"%s",__func__);

    UITouch * touch = [touchesanyObject];    

    CGPoint point = [touchlocationInView:self.superview];//每隔一定的时间段都会执行此代码,所以在整个移动过程中会记录很多经过的点(记录的坐标相对于父视图)

    [selfsetFrame:CGRectMake(point.x -_beginPoint.x, point.y -_beginPoint.y,self.frame.size.width,self.frame.size.height)];//根据开始触摸的坐标,以及移动时的坐标设置其坐标,可实现视图移动

}

//触摸事件结束时会执行的方法

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {

    NSLog(@"%s",__func__);

}

//触摸事件取消时会执行的方法(一般在触摸发生了但没结束时,有来电或其他事件导致触摸事件不自主的停止时会调用次方法)

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {

    NSLog(@"%s",__func__);

}

如何绘制例如线,三角形,矩形,圆等图形

//UIView类中同样有此类方法实现图像的绘制(CGRect 是一个结构体,包含点的X和Y坐标,宽和长两个结构体元素)

- (void)drawRect:(CGRect)rect

{

   //下两行是写字的作用(等同于输出字符串)

    NSString * str = @"hello";

    [str drawInRect:rect withAttributes:nil];

    

   //获得当前所要绘制内容的上下文(上下文可看做是草稿纸,是一个中间量)

   CGContextRef context =UIGraphicsGetCurrentContext();

   //改颜色

   CGContextSetStrokeColorWithColor(context, [UIColororangeColor].CGColor);

    //粗细

   CGContextSetLineWidth(context,4.0f);

   //获得起始点

   CGContextMoveToPoint(context,10,20);

    //终点

   CGContextAddLineToPoint(context,70,70);

    //折线的实现

   CGContextAddLineToPoint(context,80,0);

    //相当于草稿纸誊抄的过程,将上下文context中的内容在View中画出图形

   CGContextStrokePath(context);

    //画圆(长宽不等时为椭圆)

    CGContextStrokeEllipseInRect(context, CGRectMake(0, 0, 90, 60));

    //画弧

    CGContextAddArc(context,5, 5,5,0, M_2_PI,0);

   CGContextStrokePath(context);

   //矩形(实心和空心)

   CGContextFillRect(context,CGRectMake(10,10,20,30));

   CGContextStrokeRect(context,CGRectMake(10,40,20,30));

   //三角形

    CGPoint sPoints[3];//坐标点

    sPoints[0] =CGPointMake(50,20);//坐标一

    sPoints[1] =CGPointMake(95,85);//坐标2

    sPoints[2] =CGPointMake(95,25);//坐标3

    CGContextAddLines(context, sPoints,3);//添加线

   CGContextClosePath(context);//封起来

   CGContextDrawPath(context,kCGPathFillStroke);//根据坐标绘制路径

   CGContextStrokePath(context);//开始绘制

}


  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值