It implements OnTouch listener, and by using MotionEvent object gets the co-ordinates of touch point. These co-ordinates are used to get color from Image.
// Step 1: create xml layout containing a linear layout with Image view & linear layout
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:id="@+id/linearLayout"
android:layout_height="fill_parent" android:layout_width="fill_parent"
android:clickable="false">
<ImageView android:id="@+id/imgView" android:layout_width="fill_parent"
android:layout_height="380dip"></ImageView>
<LinearLayout android:orientation="horizontal"
android:layout_width="fill_parent" android:id="@+id/linearbaseRow"
android:background="@color/white" android:gravity="bottom"
android:layout_height="50dip">
</LinearLayout>
</LinearLayout>
//Step 2: in java code, implement a OnTouch listener and display color.
public class ColorPicker extends Activity {
private final int DIALOG_SINGLE_CHOICE = 0;
LinearLayout linearlayout, linearBaseRow;
ImageView imgView, showColor;
int color = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.color_picker_layout);
linearlayout = (LinearLayout) findViewById(R.id.linearLayout);
linearBaseRow = (LinearLayout) findViewById(R.id.linearbaseRow);
imgView = (ImageView) findViewById(R.id.imgView);
imgView.setBackgroundResource(R.drawable.backgroundimage);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
try {
//get access to base layout
View tempView = linearlayout.getRootView();
tempView.setDrawingCacheEnabled(true);//enable cache
Bitmap temBitmap = tempView.getDrawingCache(); //get cache
color = temBitmap.getPixel((int) event.getX(), (int) event
.getY());
showColor();
} catch (Exception Ex) {
}
return true;
}
private void showColor(){
linearBaseRow.setBackgroundColor(color);
}
@Override
protected void onDestroy() {
imgView = null;
dialog = null;
super.onDestroy();
}
}