javaandroidimageviewimage-scalinganchorpoint

Android scale ImageView using anchor points


The goal is: the Imageview have 4 squares on each corners. If the user touch and drag one of this, the image is scaled.

Given the image, the 4 squares and the touched square how can i implement this feature?
(square = Rectf class)

example of image


Solution

  • I have find out a possible solution, if anyone need the code:

    float centerX, centerY, startScale, startX, startY;
    
    private void startScaling(MotionEvent e) {
        ImageView imageView = (ImageView) getChildAt(0);
    
        switch (e.getAction()) {
            case MotionEvent.ACTION_DOWN:
                startX = e.getX();
                startY = e.getY();
                startScale = imageView.getScaleX();
                centerX = imageView.getX() + imageView.getWidth() / 2F;
                centerY = imageView.getY() + imageView.getHeight() / 2F;
                break;
    
            case MotionEvent.ACTION_MOVE:
                // euclidean distance
                double length1 = Point.distance(centerX, centerY, startX, startY);
                double length2 = Point.distance(centerX, centerY, e.getX(), e.getY());
    
                if(length2 > length1) {
                    //scale up
                    float scaleFactor = (float) (length2 / length1);
    
                    //scale the image
                    imageView.setScaleX(startScale * scaleFactor);
                    imageView.setScaleY(startScale * scaleFactor);
                }else {
                    //scale down
                    // calculate the scale factor
                    float scaleFactor = (float) (length1 / length2);
    
                    // scale the image
                    imageView.setScaleX(startScale / scaleFactor);
                    imageView.setScaleY(startScale / scaleFactor);
                }
    
                float scaledWidth = imageView.getWidth() * imageView.getScaleX();
                float scaledHeight = imageView.getHeight() * imageView.getScaleY();
    
                // calculate new boubds of the image
                float left = centerX - scaledWidth / 2F;
                float top = centerY - scaledHeight / 2F;
                float right = left + scaledWidth;
                float bottom = top + scaledHeight;
                break;
            case MotionEvent.ACTION_UP:
                break;
        }
    }