jason jason - 6 months ago 27
Android Question

Resize ImageView with only one finger movement instead of two

I'm trying to change an ImageView's height with only one finger movement (upside or downside). The code below changes height with two fingers (like pinching or reverse). How can I modify this code to do what I want? Thanks.

public class MainActivity extends Activity {


private ImageView iv;
private Matrix matrix = new Matrix();
private float scale = 1f;
private ScaleGestureDetector SGD;



@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

iv = iv=(ImageView)findViewById(R.id.imageView);
SGD = new ScaleGestureDetector(this, new ScaleListener());

}

public boolean onTouchEvent(MotionEvent ev) {
SGD.onTouchEvent(ev);
return true;
}

private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener
{
@Override
public boolean onScale(ScaleGestureDetector detector) {
scale *= detector.getScaleFactor();
scale = Math.max(0.1f, Math.min(scale, 5.0f));

matrix.setScale(1, scale);
iv.setImageMatrix(matrix);
return true;
}
}
}

Answer

Use GestureDetector for scroll:

@Bind(R.id.container)
ViewGroup container;

@Bind(R.id.image)
ImageView image;
private GestureDetectorCompat detector;
private float yscale = 1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);
    ButterKnife.bind(this);
    image.setScaleType(ImageView.ScaleType.MATRIX);

    detector = new GestureDetectorCompat(this, new GestureDetector.SimpleOnGestureListener() {

        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
            Matrix m = new Matrix();
            yscale += distanceY / container.getHeight();
            m.setScale(1, yscale, 0, 0);
            image.setImageMatrix(m);
            return true;
        }
    });
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    return detector.onTouchEvent(event);
} detector.onTouchEvent(event);
}
Comments