关于Android中ImageView的一个奇怪的事情

时间:2014-03-10 06:07:51

标签: android imageview zoom

最近,我完成了自己的ImageView。它可以被拖放或缩放,但是当我将这个apk安装到我的手机时,这个ImageView总是在我想要缩放时摇晃。(我不擅长英语,抱歉)。谢谢你的帮助

以下是ImageView的子类:

      public class MyImageView extends ImageView {

private MODE mode = MODE.NONE; 
private PointF startPoint = new PointF(); 
private float distance = 0; 
private float scale; 
public MyImageView(Context context) {
    super(context);
    this.setPadding(10, 10, 10, 10);
    this.setScaleType(ScaleType.FIT_XY);
    this.setImageResource(R.drawable.emoji_18);
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    if (!isEnabled())
        return false;
    switch (event.getAction() & MotionEvent.ACTION_MASK) {
    case MotionEvent.ACTION_DOWN:
        mode = MODE.DRAG; 
        startPoint.set(event.getRawX(), event.getRawY());
        break;
    case MotionEvent.ACTION_MOVE:
        if (mode == MODE.DRAG) {
            drag(event);
        }
        if (mode == MODE.ZOON_ROTATION && event.getPointerCount() == 2) {
            zoon(event);
        }
        break;
    case MotionEvent.ACTION_POINTER_DOWN:
        distance = distance(event);
        scale = this.getScaleX();
        mode = MODE.ZOON_ROTATION;
        break;
    case MotionEvent.ACTION_POINTER_UP:
        mode = MODE.NONE;
        break;
    case MotionEvent.ACTION_UP:
    default:
        break;
    }
    return true;
}

private void zoon(MotionEvent event) {
    float currentDistance = distance(event);
    float currentScale = currentDistance / distance;
    currentScale = scale * currentScale;
    this.setScaleX(currentScale);
    this.setScaleY(currentScale);

}

private void drag(MotionEvent event) {
    PointF endPoint = new PointF();
    endPoint.set(event.getRawX(), event.getRawY());
    float dx = endPoint.x - startPoint.x;
    float dy = endPoint.y - startPoint.y;
    startPoint.set(endPoint);
    this.setTranslationX(this.getTranslationX() + dx);
    this.setTranslationY(this.getTranslationY() + dy);
    this.invalidate();
}

private float distance(MotionEvent event) {
    float dx = event.getX(0) - event.getX(1);
    float dy = event.getY(0) - event.getY(1);
    return FloatMath.sqrt(dx * dx + dy * dy);
}

private enum MODE {
    NONE, DRAG, ZOON_ROTATION; 
}

    }

以下是MainActivity:

           public class MainActivity extends Activity {

private FrameLayout frameLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.setContentView(R.layout.activity_main);
    frameLayout=(FrameLayout) findViewById(R.id.framelayout);
    MyImageView myView= new MyImageView(this);
    frameLayout.addView(myView , 300 ,300);
    myView= new MyImageView(this);
    frameLayout.addView(myView , 300 , 300);

}
      }

以下是布局:

 FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" 
android:id="@+id/framelayout"
>

0 个答案:

没有答案