Know the size of an image on Android

1

I'm developing an application on Android. I need to get the RGB of a particular image at 5 specific points in the image. as shown below:

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

    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 above illustration are just an example!

  • / li>

My question is:

  • How can I capture the dimensions of an image? That is, its dimensions in width and height?
  • asked by anonymous 19.08.2017 / 00:29

    1 answer

    1

    Considering at first that you are using ImageView , one option is to create a variable of type ViewTreeObserver and use the addOnPreDrawListener method to stay "watching and listening" to the specific view as it launches in the application, regardless of device resolution. See:

    • getMeasuredHeight() : Retrieves height of ImageView
    • getMeasuredWidth() : Retrieves 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"
        />
    

    No 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
        }
    })
    
        
    19.08.2017 / 01:16