Make Screen Compatibility Containing Canvas

2019-05-31 11:31发布

问题:

I am working with canvas in android. i want to draw shapes on canvas which fits in every screen.

if screen size is 320 * 240 then height & width with is 90 * 90 but

if screen_size is > 320 * 240 then it should increase accordingly.

Suppose screen_size = 1280 * 800 then how much it should increase

I don't know what to do for this

Code is Like

int fixHeight = 240, fixWidth = 320;
Paint paint;
paint = new Paint();
paint.setColor(Color.GREEN);
DisplayMetrics displaymetrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int height = displaymetrics.heightPixels;
int width = displaymetrics.widthPixels;
@Override
protected void onDraw(Canvas canvas) {
     if (height <= fixHeight && width <= fixWidth) {
          canvas.drawRect(10, 10, 50, 50, paint);  
     } else {
          // Don't Know What TO Put Here
     }
}

Can any one help me

回答1:

in your onDraw method you might want to check the layout height and width of your canvas and adjust your draw.height and draw.width accordingly.

If the size has increased for the screen then you can use a multiplying factor to your draw.width and draw.height constants to either multiply or divide before drawing.

EDIT: After code was posted.

Lets say 320*240 is the base case for you to draw a rectangle of height as 40 and breadth as 40 that is canvas.drawRect(10, 10, 50, 50, paint);So left, top, right and bottom can be used to be modified in your case with a new resolution of 1280*800 using the below formula.

320 --> (50 - 10)
1280 --> (x - 10)

so x = 10 + (50-10)*1280/320

Try to repeat the same forumla for wdith and you should get your base co-ordinates. I believe you can adjust your 10, 10(which I am keeping here constant) to a new location based on the same above formula.