Different resolution support android

前端 未结 8 1335
北海茫月
北海茫月 2020-11-22 04:21

Edited Question:

Mobile Resolution:
I would like to design different screen dpi like following resolutions.
320x480,
48

8条回答
  •  别那么骄傲
    2020-11-22 04:55

    To avoid the problems of different screen resolutions and different densities, I size and position everything based on the percentage width and height of the screen. If text is resized based on the percentage width or height of the screen, the font will be the correct size on all devices and all resolutions. To get the correct font size based on a width and height of its space, simply use this function:

    private float SetTextSize(String text, int width, int height)
    {
        Paint paint = new Paint();
        float textWidth = paint.measureText(text);
        float textSize = (int) ((width / textWidth) * paint.getTextSize());
        paint.setTextSize(textSize);
    
        textWidth = paint.measureText(text);
        textSize = (int) ((width / textWidth) * paint.getTextSize());
    
        // Re-measure with font size near our desired result
        paint.setTextSize(textSize);
    
        // Check height constraints
        FontMetricsInt metrics = paint.getFontMetricsInt();
        float textHeight = metrics.descent - metrics.ascent;
        if (textHeight > height)
        {
            textSize = (int) (textSize * (height / textHeight));
            paint.setTextSize(textSize);
        }
        return textSize;
    }
    

    Here's the code to get the width and height of the screen:

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2)
    {
        Point size = new Point();
        getWindowManager().getDefaultDisplay().getSize(size);
        screenWidth = size.x;
        screenHeight = size.y; 
    }
    else
    {
        Display display = getWindowManager().getDefaultDisplay(); 
        screenWidth = display.getWidth(); 
        screenHeight = display.getHeight(); 
    }
    

    To get the font size you want, simply make up an area based on the screen width and screen height and tweak it until the font size looks right. Once you get it looking right, it should look right on all devices.

    float textSize = SetTextSize("text", (int) (screenWidth * 0.1), (int) (screenHeight * 0.15));
    

    I hope this helps you

提交回复
热议问题