欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android 图片显示与屏幕适配的问题

程序员文章站 2023-12-09 20:37:27
android 图片显示与屏幕适配的问题 在android开发中比较头疼的是android的分辨率问题,那么这里给大家介绍个万能办法,这个办法的优点是可以实现万能适应,给...

android 图片显示与屏幕适配的问题

在android开发中比较头疼的是android的分辨率问题,那么这里给大家介绍个万能办法,这个办法的优点是可以实现万能适应,给开发和美工设计提供了依据,但是对开发来说代码量也不少,具体办法:

(1)获取屏幕的尺寸

windowmanager windowmanager = (windowmanager)     getsystemservice(context.window_service);
display d = windowmanager.getdefaultdisplay();
mwidth = d.getwidth();mheight = d.getheight();
displaymetrics dm = getresources().getdisplaymetrics()
mscreendensity = dm.density;

(2)美工设计图的尺寸

uiwidth,uiheight

(3)获取缩放比例

float scalewidth = mwidth / uiwidth;
float scaleheight = mheight/ uiheight;

(4)所有布局的尺寸用代码实现:

public static int getwidthsize(int size) {
        return (int) (size * scalewidth);
    }

    public static int gethightsize(int size) {
        return (int) (size * scaleheight);
    }

    public static float gettextsize(int pxsize) {
        return (pxsize * scaleheight) / mscreendensity;
    }

    public static void setviewsize(int width, int height, view v) {
        int paramwidth = getwidthsize(width);
        int paramheight = gethightsize(height);
        viewgroup.marginlayoutparams params = (viewgroup.marginlayoutparams) v
                .getlayoutparams();
        if (width != invalid) {
            params.width = paramwidth;
        }
        if (height != invalid) {
            params.height = paramheight;
        }
        v.setlayoutparams(params);
    }

    public static void setviewpadding(int left, int top, int right, int bottom,
            view v) {
        left = getwidthsize(left);
        top = gethightsize(top);
        right = getwidthsize(right);
        bottom = getwidthsize(bottom);
        v.setpadding(left, top, right, bottom);
    }

    public static void setviewmargin(int left, int top, int right, int bottom,
            view v) {
        int paramleft = getwidthsize(left);
        int paramtop = gethightsize(top);
        int paramright = getwidthsize(right);
        int parambottom = gethightsize(bottom);
        viewgroup.marginlayoutparams params = (viewgroup.marginlayoutparams) v
                .getlayoutparams();
        if (left != invalid) {
            params.leftmargin = paramleft;
        }
        if (right != invalid) {
            params.rightmargin = paramright;
        }
        if (top != invalid) {
            params.topmargin = paramtop;
        }
        if (bottom != invalid) {
            params.bottommargin = parambottom;
        }
        v.setlayoutparams(params);}

(5)这里是设置尺寸的代码:

setviewsize(100, 100, mview);
    setviewmargin(20, 0, 0, 20, mview);
    setviewpadding(10, 10, 10, 10, mview);
    mtextview.settextsize(gettextsize(30));

由上在设计效果图时,可对图内元素进行尺寸标注,程序即可实现按比例缩放。

以上就是android 图片显示与屏幕适配的问题的万能解决办法,如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!