2

如何从CustomViewBitmap中的例程中提取对象?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); 在构造函数但没有工作,再次感谢;)

4

1 回答 1

3

没有办法从画布中提取位图。至少不是直接的。

但是,可以使用绘制位图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)。

于 2014-02-20T17:34:18.537 回答