如何访问onDraw方法Android之外的画布宽度

时间:2014-05-09 05:58:43

标签: java android canvas initialization width

我有以下代码:

Bitmap right1;

public TicTacToe(Context context) {
    super(context);
    right1 = BitmapFactory.decodeResource(getResources(), R.drawable.plus);
    int width = right1.getWidth();
    int height = right1.getHeight();
}

@Override
protected void onDraw(Canvas canvas){
    super.onDraw(canvas);
    canvas.drawColor(Color.WHITE);
    right1 = Bitmap.createScaledBitmap(right1, canvas.getWidth()/3, canvas.getWidth()/3, false);
    canvas.drawBitmap(right1, (canvas.getWidth() - (canvas.getWidth()/3)), 0, null);
    invalidate();
}

我想重新调整名为" right1"的位图。基于画布的宽度。我成功地做到了这一点,但执行此操作的代码行是onDraw方法下的第三行。这行代码的问题在于,当我只想运行一次时,它会不断循环。理想我想把这行代码放在TicTacToe方法中,但我不确定如何在TicTacToe方法中初始化画布,以便我可以获得画布宽度。

1 个答案:

答案 0 :(得分:1)

你不需要在构造函数中做这个东西只需在onDraw()方法中添加条件。

@Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawColor(Color.WHITE);

        if(right1==null){
            right1 = Bitmap.createScaledBitmap(right1, canvas.getWidth() / 3, canvas.getWidth() / 3, false);
            canvas.drawBitmap(right1, (canvas.getWidth() - (canvas.getWidth() / 3)), 0, null);
            invalidate();
        }
    }