如何在我的CustomView中從我的onDraw()
例程中提取出Bitmap
對象?如何從視圖的onDraw()方法中提取位圖?
這裏是我的代碼:
public class DrawView extends View {
private Paint paint = new Paint();
private Point point;
private LinkedList<Point> listaPontos;
private static Context context;
class Point {
public Point(float x, float y) {
this.x = x;
this.y = y;
}
float x = 0;
float y = 0;
}
public DrawView(Context context) {
super(context);
this.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT));
this.context = context;
paint.setColor(Color.YELLOW);
this.listaPontos = new LinkedList<Point>();
}
@Override
public void onDraw(Canvas canvas) {
if(listaPontos.size() != 0){
for(Point point : listaPontos){
canvas.drawCircle(point.x, point.y, 25, paint);
}
}
calculateAmount(canvas);
}
private void calculateAmount(Canvas canvas) {
LinkedList<Integer> colors = new LinkedList<Integer>();
for(int i = 0 ; i != canvas.getWidth(); i++)
{
for(int j = 0; j != canvas.getHeight(); j++){
int color = BITMAP.getPixel(i,j); //How can I get the bitmap generated on onDraw ?
colors.add(color);
}
}
int yellow = 0;
int white = 0;
for(Integer cor : colors) {
if(cor == Color.WHITE) {
white++;
}
if(cor == Color.YELLOW) {
yellow++;
}
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_MOVE:
listaPontos.add(new Point(event.getX(), event.getY()));
break;
}
invalidate();
return true;
}
}
非常感謝提前;)
編輯:位圖的是要計算每個像素的顏色,我該怎麼添加背景圖片到我的drawView函數?我測試了this.setBackgroundResource(R.drawable.a);在構造函數但沒有工作,再次感謝;)
您也可以在.xml中設置背景圖片,只需設置android:background =「@ drawable/your_drawable」。同時請注意,DrawView中的繪製內容可能覆蓋背景圖片。 –
我是不使用xml,mBitmapCanvas.drawColor(Color.WHITE);擦除內容,我現在使用位圖添加圖像b = BitmapFactory.decodeResource(getResources(),R.drawable.a); mBitmapCanvas.drawBitmap(b,0,0,paint);但圖像被拉長了..沒有最大化爲什麼? – TiagoM
以下是如何從資源中正確加載位圖:http://pastebin.com/LsEWpSMq只需使用位圖b = BitmapResloader.decodeBitmapFromResource(資源res,int resId,int reqWidth,int reqHeight);另外,如果回答原始問題,請選擇我的答案爲正確。 –