Is it possible to calculate number of pixels in a specific portion of screen?? say i draw a circle and want to calculate no. of pixels inside the circle!
Asked
Active
Viewed 257 times
1
-
Have you seen this [**SO answer**](http://stackoverflow.com/questions/8295986/how-to-calculate-dp-from-pixels-in-android-programmatically)? – silentw Jul 22 '13 at 10:26
-
@ShivanRaptor i know how to calculate no. if pixel of whole screen but i dun knw how to perform the same for a specific portion – Gunjit Dhawan Jul 22 '13 at 10:30
2 Answers
1
You can get the width and height of a view but it depends how you're drawing the circle. If you're drawing it on a Canvas you can calculate the area of the circle using:
area = Π x r(2)
All you need is the radius of the circle and use 3.1415927 as the value of Pi.

Scott Helme
- 4,786
- 2
- 23
- 35
-
i had to discard the concept of area..bcoz by this method we cant calculate area of irregular figures – Gunjit Dhawan Jul 22 '13 at 10:33
-
-
-
If you have a fixed background colour and the 'shape' you want to count the pixels of is a fixed colour you can export the canvas to a bitmap and then step through the value of each pixel. So, if the background is black, and you're drawing in red, count through all pixels and total the red pixels. – Scott Helme Jul 22 '13 at 10:48
-
-
but what if the user draws an image on canvas and then we have to calculate the number of pixels – Gunjit Dhawan Jul 22 '13 at 10:52
0
Push the canvas to a bitmap then count the pixels:
public static Bitmap getBitmapFromView(View v) {
Bitmap b = Bitmap.createBitmap( v.getLayoutParams().width, v.getLayoutParams().height, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
v.layout(0, 0, v.getLayoutParams().width, v.getLayoutParams().height);
v.draw(c);
return b;
}
That will get you the bitmap, then step through each pixel and count the colour you're looking for:
for(int x = 0; x < b.getWidth(); x++){
for(int y = 0; y < b.getHeight(); y++){
int pixel = b.getPixel(x,y);
int r = Color.red(pixel);
int g = Color.green(pixel);
int b = Color.blue(pixel);
//test against your colour here and increment counter
}
}
I don't have an IDE to hand so the code may be a bit rough but it will put you on the right lines.

Scott Helme
- 4,786
- 2
- 23
- 35