Before Pixel Color Replacement
After Pixel Color Replacement
Create new Android Project
Project Name: PlayingwithBitmap
Build Target: Android 2.3.3 //or greater than that
Application Name: PlayingwithBitmap
Package Name: com.shaikhhamadali.blogspot.playingwithbitmap
Create Activity: Main
Min SDK: 10 // or greater than that
- create main layout:
- One image view to display the image.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff" >
<ImageView
android:id="@+id/imViewAndroid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:src="@drawable/car" />
</RelativeLayout>
package com.shaikhhamadali.blogspot.playingwithbitmaps;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.Menu;
import android.widget.ImageView;
public class Main extends Activity {
ImageView imViewAndroid;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imViewAndroid = (ImageView) findViewById(R.id.imViewAndroid);
Bitmap b=replaceColor(BitmapFactory.decodeResource(getResources(), R.drawable.basic),Color.YELLOW,Color.MAGENTA);
imViewAndroid.setImageBitmap(b);
}
public Bitmap replaceColor(Bitmap src,int fromColor, int targetColor) {
if(src == null) {
return null;
}
// Source image size
int width = src.getWidth();
int height = src.getHeight();
int[] pixels = new int[width * height];
//get pixels
src.getPixels(pixels, 0, width, 0, 0, width, height);
for(int x = 0; x < pixels.length; ++x) {
pixels[x] = (pixels[x] == fromColor) ? targetColor : pixels[x];
}
// create result bitmap output
Bitmap result = Bitmap.createBitmap(width, height, src.getConfig());
//set pixels
result.setPixels(pixels, 0, width, 0, 0, width, height);
return result;
}
}
3. note that:
- With the help of this,replaceColor() method you can Replace the color of image on image on click,on action_down,on the fly etc.
- You can cut the required area of image by changing their color into Color.Transparent.
4. conclusion:
- Some information about Color Replacement.
- Know how to Replace image bitmap colors from drawables.
5. About the post:
- The code seems to explain itself due to comments, and is very easy to understand.
- Don’t mind to write a comment whatever you like to ask, to know,to suggest or recommend.
- Hope you enjoy it!
Hamad Ali Shaikh