Reputation: 23
I am trying to change the color of a bitmap based on a hex value.
before i attempt to us myBitmap.setPixel with the color chosen in my color picker, im just trying to get it working with an rgb like so:
for (int x = 0; x <= myBitmap.getWidth(); x++) {
for (int y = 0; x <= myBitmap.getHeight(); y++) {
myBitmap.setPixel(x, y, Color.rgb(255, 255, 255));
}
}
if I set just one pixel like so:
bitmapPreview.setPixel(50, 50, Color.rgb(255, 255, 255));
it works just fine, but when i attempt to loop through the bitmap pixels it force closes the application
any suggestion on how to make this work, or another recommendation on how i can change the color of a bitmap based on a value returned from a color chooser. the format of the value returned from the color chooser is this : white = -1 or a blue shade = -15658590
thanks!
Upvotes: 2
Views: 3945
Reputation: 4291
If this is the exact code you are using, your loop conditions are wrong. You are exceeding the limits of the bitmap by 1 pixel in both dimensions, and you have used the wrong variable to check one of the dimensions. Change <=
to <
in both loops, and change x
in the second for condition to y
:
for (int x = 0; x < myBitmap.getWidth(); x++) {
for (int y = 0; y < myBitmap.getHeight(); y++) {
myBitmap.setPixel(x, y, Color.rgb(255, 255, 255));
}
}
Upvotes: 7
Reputation: 1812
The reason behind application force close is you are performing CPU intensive operation. your long running operation should be always performed in AsyncTask and not on UI thread of application.
Option 1:
create a Sub class of AsyncTask<> class and do your pixel operation in doInBackground method. that will not force close the application
Option 2 : (Better choice for Bitmap operation )
use RenderScript for performing such graphic operation. RenderScript is cross platform and can perform pixel operation faster than looping in java code.
Upvotes: 3