Reputation: 703
I have the following code:
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();
}
I want to rescale the bitmap that is called "right1" based off of what the width of the canvas is. I succeeded in doing this, but the line of code that does this is the third line under the onDraw method. The problem with that line of code is that it will constantly loop when I would like to only run it once. Idealy I would like to put that line of code within the TicTacToe method, but I am unsure how to initialize the canvas within the TicTacToe method so that I can get the canvas width.
Upvotes: 1
Views: 717
Reputation: 28484
You don't need to do this stuff inside constructor just add condition in onDraw() method.
@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();
}
}
Upvotes: 1