Android ScreenUtils获取屏幕的宽高,SizeUtil计算出一个等比例的最大区域

package com.zhangyu.myopengl.utils;

import android.content.Context;
import android.util.DisplayMetrics;

public class ScreenUtils {
    /**
     * 获取屏幕的宽高
     *
     * @param context
     * @return
     */
    public static int[] getScreenSize(Context context) {
        DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
        return new int[]{displayMetrics.widthPixels, displayMetrics.heightPixels};
    }

    public static int getScreenHeight(Context context) {
        return getScreenSize(context)[1];
    }

    public static int getScreenWidth(Context context) {
        return getScreenSize(context)[0];
    }

package com.zhagyu.opencut.utils;

import android.content.res.Resources;

public class SizeUtils {

    /**
     * 在一个可用的区域内,计算出一个比例为 ratio 的最大的宽高。
     *
     * @param ratio     ratio = (float) srcHeight / (float) srcWidth;
     * @param maxWidth  可用的最大区域的宽度
     * @param maxHeight 可用的最大区域的高度
     * @return
     */
    public static int[] getMaxSize(float ratio, int maxWidth, int maxHeight) {
        int width = 0;
        int height = 0;
        for (int i = 0; i < 20; i++) {
            width = (int) (maxWidth * (1 - i * 0.05));
            height = (int) (width * ratio);
            if (height < maxHeight) {
                break;
            }
        }
        return new int[]{width, height};
    }

    /**
     * Value of dp to value of px.
     *
     * @param dpValue The value of dp.
     * @return value of px
     */
    public static int dp2px(final float dpValue) {
        final float scale = Resources.getSystem().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * Value of px to value of dp.
     *
     * @param pxValue The value of px.
     * @return value of dp
     */
    public static int px2dp(final float pxValue) {
        final float scale = Resources.getSystem().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值