Know the size of an image on Android

Asked

Viewed 203 times

1

I am developing an application on Android. I need to get the RGB of a certain image in 5 specific points of the image. as shown below:

inserir a descrição da imagem aqui

I am using the following code to capture the image RGB:

    int color = bitmap.getPixel(x, y);

    int red = Color.red(color);
    int blue = Color.blue(color);
    int green = Color.green(color);
    int alpha = Color.alpha(color);
  • The points defined in the illustration above are just an example!

  • I imagine that to determine the point I want to get the RGB, that is, the points set by me, i need to know what the dimensions of an image.

My point is:

  1. How can I capture the dimensions of an image? That is, its dimensions in width and height?
  • https://developer.android.com/training/material/palette-colors.html

1 answer

1


Considering, at first, that you’re using a ImageView, an option is to create a variable of type ViewTreeObserver and use the method addOnPreDrawListener to be "watching and listening" to view specific as it is launched into the application, regardless of device resolution. See:

  • getMeasuredHeight() : Rescues the height of ImageView
  • getMeasuredWidth() : Rescues the length of ImageView

See below:

final ImageView iv = (ImageView)findViewById(R.id.iv);
ViewTreeObserver vto = iv.getViewTreeObserver();
vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
    public boolean onPreDraw() {
        iv.getViewTreeObserver().removeOnPreDrawListener(this);

        int height = iv.getMeasuredHeight();
        int width = iv.getMeasuredWidth();

        return true;
    }
});

XML

<ImageView
    android:id="@+id/iv"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:src="@mipmap/ic_launcher"
    />

In the Kotlin using Extensions, This is much simpler. See:

iv.viewTreeObserver.addOnPreDrawListener(object : ViewTreeObserver.OnPreDrawListener {
    override fun onPreDraw(): Boolean {
        iv.viewTreeObserver.removeOnPreDrawListener(this)
        val height = iv.measuredHeight
        val width = iv.measuredWidth

        return true
    }
})

Browser other questions tagged

You are not signed in. Login or sign up in order to post.