get Bitmap Rect From Image View - Android User Interface

Android examples for User Interface:ImageView

Description

get Bitmap Rect From Image View

Demo Code


//package com.java2s;

import android.graphics.Bitmap;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;

import android.widget.ImageView;

public class Main {
    public static Rect getBitmapRectFromImageView(ImageView imageView) {
        Drawable drawable = imageView.getDrawable();
        Bitmap bitmap = null;//  w w w.ja v a2s.  c o  m
        if (drawable instanceof BitmapDrawable) {
            bitmap = ((BitmapDrawable) drawable).getBitmap();
        }

        Rect rect = new Rect();
        boolean result = imageView.getGlobalVisibleRect(rect);

        boolean checkWidth = rect.width() < imageView.getWidth();
        boolean checkHeight = rect.height() < imageView.getHeight();

        boolean clipped = !result || checkWidth || checkHeight;

        if (bitmap != null && !clipped) {

            int bitmapWidth = bitmap.getWidth();
            int bitmapHeight = bitmap.getHeight();

            int imageViewWidth = imageView.getWidth();
            int imageviewHeight = imageView.getHeight();

            float startScale;
            if ((float) imageViewWidth / bitmapWidth > (float) imageviewHeight
                    / bitmapHeight) {
                // Extend start bounds horizontally
                startScale = (float) imageviewHeight / bitmapHeight;

            } else {
                startScale = (float) imageViewWidth / bitmapWidth;

            }

            bitmapHeight = (int) (bitmapHeight * startScale);
            bitmapWidth = (int) (bitmapWidth * startScale);

            int deltaX = (imageViewWidth - bitmapWidth) / 2;
            int deltaY = (imageviewHeight - bitmapHeight) / 2;

            rect.set(rect.left + deltaX, rect.top + deltaY, rect.right
                    - deltaX, rect.bottom - deltaY);

            return rect;
        } else {
            return null;
        }

    }
}

Related Tutorials