Reputation: 35
I'm quite new to Android and am doing my own mini-project and I want to change a specific pixel's color. searching for how to do so, I came across this question from a couple of years back. I tried myBitmap.setPixel(10, 10, Color.rgb(45, 127, 0));
, but when I am actually activating it on my phone, it just crashes the second I activate this line of code. It seems to crash whenever I'm interacting with the bitmap. int x =myBitmap.getHeight();
this line also crashes the app.
Yet, the initial creation of the bitmap doesn't cause any problems:
background = (ImageView) findViewById(R.id.dangeon);
background.setDrawingCacheEnabled(true);
background.buildDrawingCache(true);
dang = background.getDrawingCache();
Do I have to install any package or activate anything to use the setPixel or getHeight functions? Alternatively, is there any other way to change a specific pixel?
logcat error when trying @jayanth suggestion:
2021-10-09 20:23:18.276 24894-24894/Aviv.Aviv E/AndroidRuntime: FATAL EXCEPTION: main Process: Aviv.Aviv, PID: 24894 java.lang.NullPointerException: Attempt to invoke virtual method 'android.graphics.Bitmap android.graphics.Bitmap.copy(android.graphics.Bitmap$Config, boolean)' on a null object reference at Aviv.Aviv.MainActivity.onClick(MainActivity.java:247) at android.view.View.performClick(View.java:7339) at android.view.View.performClickInternal(View.java:7305) at android.view.View.access$3200(View.java:846) at android.view.View$PerformClick.run(View.java:27787) at android.os.Handler.handleCallback(Handler.java:873) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:214) at android.app.ActivityThread.main(ActivityThread.java:7089) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:965)
Upvotes: 0
Views: 1050
Reputation: 6307
If you are trying setPixel()
method on the immutable bitmap. it will throw a IllegalStateException
.
first, create a mutable copy of your bitmap. and then you can change the color of the pixel in your bitmap.
Bitmap mutableBitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
int red = 255; //replace it with your color
int green = 255; //replace it with your color
int blue = 255; //replace it with your color
int color = Color.argb(0xFF, red, green, blue);
mutableBitmap.setPixel(indexI, indexJ, color);
//now if you apply it to any image view to see change.
imageView.setImageBitmap(mutableBitmap);
Upvotes: 1