问题
I have a layout with the color palette as the background.
Within the layout I added a smaller image as a thumb (which is resized using @dimen
to make it smaller, really small, like a crosshair) which should move around as the user drag around the layout above:
How do I use the layout's background as a bitmap so I can use the following code:
f = (FrameLayout) findViewById(R.id.fl);
f.setOnTouchListener(flt);
iv = (ImageView) findViewById(R.id.iv);
View.OnTouchListener flt = new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
float x = event.getX();
float y = event.getY();
//int pixel = resizedbitmap.getPixel((int)x,(int) y); //the background of the layout goes here...
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (x<0) {
x = x + 10;
iv.setX(x);
iv.setY(y);
}
if (x>f.getWidth()) {
x = x - 10;
iv.setX(x);
iv.setY(y);
}
else {
iv.setX(x);
iv.setY(y);
}
// Write your code to perform an action on down
break;
case MotionEvent.ACTION_MOVE:
if (x<0) {
x = x + 10;
iv.setX(x);
iv.setY(y);
inRed = Color.red(pixel);
inBlue = Color.blue(pixel);
inGreen = Color.green(pixel);
Log.d("Colors","R:" +inRed +" G:" +inGreen+" B:" + inBlue);
}
if (x>f.getWidth()) {
x = x - 10;
iv.setX(x);
iv.setY(y);
}
else {
iv.setX(x);
iv.setY(y);
}
// Write your code to perform an action on contineus touch move
break;
case MotionEvent.ACTION_UP:
// Write your code to perform an action on touch up
break;
}
// TODO Auto-generated method stub
return true;
}
};
The XML is:
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/palette2"
android:id="@+id/fl" >
<ImageView
android:id="@+id/iv"
android:layout_width="10dp"
android:layout_height="10dp"
android:src="@drawable/esquare" />
</FrameLayout>
What I am looking to do is, create a color picker so as the user drags within the layout, the user is presented with the R G B values. Can anyone help me complete the codes?
回答1:
Get the pixel with a line like the one you commented out. Use BitMap's getPixel(x,y). You need to keep a bitmap around for this.
getPixel() returns a color int, as you can see by checking http://developer.android.com/reference/android/graphics/Bitmap.html Actually, the documentation wrongly suggests that getPixel returns an android.graphics.Color object. It does not. It returns a color int argb.
get the components of the color int, c, by calls like this, as you can see by checking http://developer.android.com/reference/android/graphics/Color.html
int alpha = Bitmap.alpha(c);
int red = Bitmap.red(c);
Or you can do the bit ops yourself:
int alpha = c >>> 24;
int red = (c >>> 16) & 0xFF;
Does that answer your question?
来源:https://stackoverflow.com/questions/21567226/how-to-use-a-layouts-background-as-a-bitmap-to-convert-x-and-y-to-rgb-values