如何从CustomView中的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);在构造函数但没有工作,再次感谢;)答案 0 :(得分:2)
无法从画布中提取位图。至少不是直接提取。
但是,可以使用Canvas
绘制位图,然后使用Bitmap
。
Bitmap mDrawBitmap;
Canvas mBitmapCanvas;
Paint drawPaint = new Paint();
@Override
public void onDraw(Canvas canvas) {
drawPaint.setColor(Color.RED);
if (mDrawBitmap == null) {
mDrawBitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
mBitmapCanvas = new Canvas(mDrawBitmap);
}
// clear previously drawn stuff
mBitmapCanvas.drawColor(Color.WHITE);
// draw on the btimapCanvas
mBitmapCanvas.drawStuff(...);
//... and more
// after drawing with the bitmapcanvas,
//all drawn information is stored in the Bitmap
// draw everything to the screen
canvas.drawBitmap(mDrawBitmap, 0, 0, drawPaint);
}
onDraw()
方法完成后,所有绘制的信息都将在屏幕上绘制(通过调用canvas.drawBitmap(...)
,并存储在Bitmap
对象中(因为所有绘制操作都有已在使用Canvas
创建的Bitmap
上完成。