我有以下XML:
<LinearLayout
android:id="@+id/llColorSpect"
android:layout_width="match_parent"
android:layout_height="@dimen/color_scheme_height"
android:orientation="vertical"
android:background="@drawable/colorspect"
android:layout_marginRight="@dimen/activity_horizontal_margin"
android:layout_marginLeft="@dimen/activity_horizontal_margin"
android:layout_marginBottom="@dimen/seek_bar_margin"
android:layout_below="@+id/tvBGColor" >
<RelativeLayout
android:id="@+id/rlColorSpect"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="@+id/ivSquare"
android:layout_width="@dimen/title_text_pad"
android:layout_height="@dimen/title_text_pad"
android:layout_alignParentBottom="true"
android:scaleType="fitXY"
android:src="@drawable/esquare" />
</RelativeLayout>
</LinearLayout>
显示以下输出:
我尝试设置画布,这样我就可以让用户在布局周围拖动小方块了:
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
public class CanvasView extends View {
private Bitmap bitmap;
private Bitmap square;
private float mScaleFactor = 1f;
int x = 0;
int y = 0;
public CanvasView(Context c) {
super(c);
bitmap= BitmapFactory.decodeResource(c.getResources(), R.drawable.colorspect);
square = BitmapFactory.decodeResource(c.getResources(), R.drawable.esquare);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.scale(mScaleFactor, mScaleFactor);
canvas.drawBitmap(bitmap, 0, 0, null);
canvas.drawBitmap(square, x, y, null);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
Log.d("x and y", "X: " + x + " Y: " + y);
int pixel = bitmap.getPixel((int)x,(int) y);
int redValue = Color.red(pixel);
int blueValue = Color.blue(pixel);
int greenValue = Color.green(pixel);
Log.d("Colors","R:" +redValue +" B:" + blueValue + " G:" +greenValue);
//Draw onto the square onto image
this.x = (int) x;
this.y = (int) y;
invalidate();
return true;
}
}
我从我的主函数调用上面的代码如下:
CanvasView canvasView = new CanvasView(this);
RelativeLayout rlDragDrop = (RelativeLayout) findViewById(R.id.rlColorSpect);
rlDragDrop.addView(canvasView);
布局不会像上图所示保持相同的布局,而是如下所示:
我要做的是,获取方形的X和Y坐标并将其转换为R,G,B值。 (这是有效的,除了我上面提到的两个问题)
答案 0 :(得分:0)
您尝试实施的内容看起来像一个颜色选择器。我敢肯定,那里有很多解决方案:) Android Color Picker
关于你的代码,最好直接子类化一个简单View的ImageView。因此ImageView会为您绘制一个背景图像(所有xml属性都是可用的),您只需要对您的方块进行处理。
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawBitmap(square, x, y, null);
}
您的第二个问题可能因canvas.scale(mScaleFactor, mScaleFactor);
而产生,但我不确定:)实际上,如果您迫切需要扩展,最好使用Canvas#drawBitmap(Bitmap, Rect, RectF, Paint)
甚至Canvas.save()
和Canvas.restore()
。