How to rotate image around center point automatically with finger touch

前端 未结 3 593
小蘑菇
小蘑菇 2021-01-17 04:38

On iPhone, how to implement rotating image around the center point using finger touch ?

Just like wheel, if you put finger on the iPhone screen , then move suddenly,

3条回答
  •  深忆病人
    2021-01-17 05:20

    I was working with a "spin the bottle"-app yesterday. On the window I have a ImageView with an bottle that's suppose to response to touches and rotate the way the user swipes his finger. I struggled to get my ImageView to rotate during the touch-events (TouchesBegan, Touchesoved, TouchesEnd). I used this code in TouchesMoved to find out the angle in witch to rotate the image.

    public override void TouchesMoved (NSSet touches, UIEvent evt)
    {    
      PointF pt = (touches.AnyObject as UITouch).LocationInView(this);
    
      float x = pt.X  - this.Center.X;
      float y = pt.Y  - this.Center.Y;
      double ang =  Math.Atan2(x,y);
    
      // yada yada, rotate image using this.Transform
    }
    

    THIS IS IMPORTANT! When the ImageView rotates, even the x & y-coordinates changes. So touching the same area all the time would give me different values in the pt and prePt-points. After some thinking, googeling and reading I came up with an simple solution to the problem. The "SuperView"-property of the ImageView.

    PointF pt = (touches.AnyObject as UITouch).LocationInView(this.SuperView);
    

    Having that small change in place made it alot easier, no i can use the UITouch-metohs LocationInView and PreviousLocationInView and get the right x & y coordinates. Her is parts of my code.

    float deltaAngle;
    
    public override void TouchesMoved (NSSet touches, UIEvent evt)
    {
        PointF pt = (touches.AnyObject as UITouch).LocationInView(this.Superview);
    
        float x = pt.X  - this.Center.X;
        float y = pt.Y  - this.Center.Y;
        float ang =  float.Parse(Math.Atan2(dx,dy).ToString());
    
    
        //do the rotation
         if (deltaAngle == 0.0) {
           deltaAngle = ang;
         }
    else
        {
          float angleDif = deltaAngle - ang;
          this.Transform = CGAffineTransform.MakeRotation(angleDif);
        }   
    }
    

    Hope that helped someone from spending hours on how to figure out how to freaking rotate a bottle! :)

提交回复
热议问题