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

CommonUtils

程序员文章站 2022-05-19 15:19:02
...

共通的工具类:

  1. convertDpToPixel ----dp转px

  2. getScreenHeight ----得到屏幕的高

  3. getScreenWidth ---- 得到屏幕的宽

  4. getScreenWidths ----得到设备屏幕的宽度

  5. getScreenHeights ----得到设备屏幕的高度

  6. hideMobilePhone4 ----隐藏手机中间4位号码

  7. isMobileExact ----验证手机号(精确)

  8. getMobileInfo ----获取手机设备信息

  9. tvPtdinType ----特殊字体

package com.jhkxkd.xiaoxiao.utils;

import android.Manifest;
import android.app.Activity;
import android.app.Service;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.NinePatch;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.NinePatchDrawable;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Build;
import android.os.Vibrator;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

import com.jhkxkd.xiaoxiao.App;
import com.jhkxkd.xiaoxiao.R;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


import static android.content.Context.INPUT_METHOD_SERVICE;


/**
 * Created by damon on 2018/4/16.
 */

public class CommonUtils {
    public static final String TAG = "MMOLIVE";
    
    // 限制6-16个字符
    private static final String REGEX_NICK_EXACT = "^(?!.*\\s).{6,16}$";

    /**
     * 提取信息中的中国电话号码(包括移动和固定电话)
     */
    private static final String REGEX_MOBILE_EXACT = "(\\(\\d{3,4}\\)|\\d{3,4}-|\\s)?\\d{7,14}";

    //6.0 权限申请
    public static void grantPermisson(Activity mContext) {
        if (Build.VERSION.SDK_INT >= 23) {
            String[] mPermissionList = new String[]{
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.READ_LOGS,
                    Manifest.permission.READ_PHONE_STATE,
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.SYSTEM_ALERT_WINDOW,
                    Manifest.permission.GET_ACCOUNTS,
                    Manifest.permission.CAMERA,
                    Manifest.permission.WRITE_SETTINGS,
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.ACCESS_COARSE_LOCATION
            };
            List<String> unGrantPermissionList = new ArrayList<String>();
            for (int i = 0; i < mPermissionList.length; i++) {
                if (ContextCompat.checkSelfPermission(mContext, mPermissionList[i])
                        != PackageManager.PERMISSION_GRANTED) {
                    unGrantPermissionList.add(mPermissionList[i]);
                }
            }
            if (unGrantPermissionList != null && unGrantPermissionList.size() > 0)
                ActivityCompat.requestPermissions(mContext, mPermissionList, 123);
        }
    }


    public static void grantPermisson(Activity mContext, String[] mPermissionList) {
        if (Build.VERSION.SDK_INT >= 23) {

            List<String> unGrantPermissionList = new ArrayList<String>();
            for (int i = 0; i < mPermissionList.length; i++) {
                if (ContextCompat.checkSelfPermission(mContext, mPermissionList[i])
                        != PackageManager.PERMISSION_GRANTED) {
                    unGrantPermissionList.add(mPermissionList[i]);
                }
            }
            if (unGrantPermissionList != null && unGrantPermissionList.size() > 0)
                ActivityCompat.requestPermissions(mContext, mPermissionList, 123);
        }
    }

    public static void grantPermisson(Activity mContext, Fragment fragment, String[] mPermissionList) {
        if (Build.VERSION.SDK_INT >= 23) {

            List<String> unGrantPermissionList = new ArrayList<String>();
            for (int i = 0; i < mPermissionList.length; i++) {
                if (ContextCompat.checkSelfPermission(mContext, mPermissionList[i])
                        != PackageManager.PERMISSION_GRANTED) {
                    unGrantPermissionList.add(mPermissionList[i]);
                }
            }
            if (unGrantPermissionList != null && unGrantPermissionList.size() > 0)
                fragment.requestPermissions(mPermissionList, 123);
        }
    }


    /**
     * 隐藏手机中间4位号码
     * 130****0000
     *
     * @param mobile_phone 手机号码
     * @return 130****0000
     */
    public static String hideMobilePhone4(String mobile_phone) {
        if (mobile_phone.length() != 11) {
            return "手机号码不正确";
        }
        return mobile_phone.substring(0, 3) + "****" + mobile_phone.substring(7, 11);
    }

    /**
     * 验证手机号(精确)
     *
     * @param string 待验证文本
     * @return {@code true}: 匹配<br>{@code false}: 不匹配
     */
    public static boolean isMobileExact(String string) {
        return isMatch(REGEX_MOBILE_EXACT, string);
    }

    /**
     * 判断是否为真实手机号
     *
     * @param mobiles
     * @return
     */
    public static boolean isMobile(String mobiles) {
        Pattern p = Pattern.compile("^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))\\\\d{8}$");
        Matcher m = p.matcher(mobiles);
        return m.matches();
    }

    /**
     * string是否匹配regex正则表达式字符串
     *
     * @param regex  正则表达式字符串
     * @param string 要匹配的字符串
     * @return {@code true}: 匹配<br>{@code false}: 不匹配
     */
    public static boolean isMatch(String regex, String string) {
        return !isNullString(string) && Pattern.matches(regex, string);
    }

    /**
     * 判断字符串是否为空 为空即true
     *
     * @param str 字符串
     * @return
     */
    public static boolean isNullString(@Nullable String str) {
        return str == null || str.length() == 0 || "null".equals(str);
    }

    /**
     * dptopx
     *
     * @param dp
     * @param context
     * @return
     */
    public static float convertDpToPixel(float dp, Context context) {
        if (context != null && context.getResources() != null) {
            Resources resources = context.getResources();
            DisplayMetrics metrics = resources.getDisplayMetrics();
            float px = dp * (metrics.densityDpi / 160f);
            return px;
        }
        return dp;
    }

    /**
     * 得到屏幕的高
     *
     * @param context
     * @return
     */
    public static int getScreenHeight(Context context) {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        int height = wm.getDefaultDisplay().getHeight();
        return height;
    }

    /**
     * 得到屏幕的宽
     *
     * @param context
     * @return
     */
    public static int getScreenWidth(Context context) {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        int width = wm.getDefaultDisplay().getWidth();
        return width;
    }

    /**
     * 得到设备屏幕的宽度
     */
    public static int getScreenWidths(Context context) {
        return context.getResources().getDisplayMetrics().widthPixels;
    }

    /**
     * 得到设备屏幕的高度
     */
    public static int getScreenHeights(Context context) {
        return context.getResources().getDisplayMetrics().heightPixels;
    }

    /**
     * 得到设备的密度
     */
    public static float getScreenDensity(Context context) {
        return context.getResources().getDisplayMetrics().density;
    }

    public static int getViewHeight(View view) {
        int intw = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        int inth = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        view.measure(intw, inth);
        int intwidth = view.getMeasuredWidth();
        int intheight = view.getMeasuredHeight();
        return intheight;
    }


    /**
     * 获得时间戳  改为秒
     */
    public static long timeStampOffset = 0;//时间戳的偏差

    public static String getTimeStamp() {
        long l = System.currentTimeMillis() / 1000 - timeStampOffset;
        return l + "";
    }

    /**
     * 获得时间戳秒单位
     */
    public static String getTimeStampSecond() {
        long l = System.currentTimeMillis() / 1000;
        return l + "";
    }


    /**
     * 保留两位小数
     *
     * @param value
     * @return
     */
    public static String format1(double value) {

        BigDecimal bd = new BigDecimal(value);
        bd = bd.setScale(2, RoundingMode.HALF_UP);
        return bd.toString();
    }

    /**
     * 服务器返回url,通过url去获取视频的第一帧
     * Android 原生给我们提供了一个MediaMetadataRetriever类
     * 提供了获取url视频第一帧的方法,返回Bitmap对象
     *
     * @param videoUrl
     * @return
     */
    public static Bitmap getNetVideoBitmap(String videoUrl) {
        Bitmap bitmap = null;

        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        try {
            //根据url获取缩略图
            retriever.setDataSource(videoUrl, new HashMap());
            //获得第一帧图片
            bitmap = retriever.getFrameAtTime();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } finally {
            retriever.release();
        }
        return bitmap;
    }


    /**
     * 获取当前本地apk的版本
     *
     * @param mContext
     * @return
     */
    public static int getVersionCode(Context mContext) {
        int versionCode = 0;
        try {
            //获取软件版本号,对应AndroidManifest.xml下android:versionCode
            versionCode = mContext.getPackageManager().
                    getPackageInfo(mContext.getPackageName(), 0).versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }

    public static String getVersionName(Context mContext) {
        String versionName = "";
        try {
            //获取软件版本号,对应AndroidManifest.xml下android:versionCode
            versionName = mContext.getPackageManager().
                    getPackageInfo(mContext.getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionName;
    }

    /**
     * 获取版本号名称
     *
     * @param context 上下文
     * @return
     */
    public static String getVerName(Context context) {
        String verName = "";
        try {
            verName = context.getPackageManager().
                    getPackageInfo(context.getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return verName;
    }
    //控制不可重复点击控件

    private static long lastClickTime;
    public static final int MIN_CLICK_DELAY_TIME = 100;

    public static boolean isFastDoubleClick() {
        long time = System.currentTimeMillis();
        long timeD = time - lastClickTime;
        if (0 < timeD && timeD < MIN_CLICK_DELAY_TIME) {
            return true;
        }
        lastClickTime = time;
        return false;
    }


    public static boolean isMatchNick(String nickName) {
        return isMatch(REGEX_NICK_EXACT, nickName);
    }

    public static int getWordCount(String s) {
        int length = 0;
        for (int i = 0; i < s.length(); i++) {
            int ascii = Character.codePointAt(s, i);
            if (ascii >= 0 && ascii <= 255)
                length++;
            else
                length += 2;

        }
        return length;

    }

    public static double getCalcuChatRatio(String chat_ratio, double num) {
        double ratio = 0.5;
        if (!TextUtils.isEmpty(chat_ratio)) {
            ratio = Double.parseDouble(chat_ratio) / 10;
        }

        return ratio * num;
    }



    //结果说明:0代表相等,1代表version1大于version2,-1代表version1小于version2
    public static int compareVersion(String version1, String version2) {
        if (version1.equals(version2)) {
            return 0;
        }
        String[] version1Array = version1.split("\\.");
        String[] version2Array = version2.split("\\.");
        int index = 0;
        // 获取最小长度值
        int minLen = Math.min(version1Array.length, version2Array.length);
        int diff = 0;
        // 循环判断每位的大小
        while (index < minLen
                && (diff = Integer.parseInt(version1Array[index])
                - Integer.parseInt(version2Array[index])) == 0) {
            index++;
        }
        if (diff == 0) {
            // 如果位数不一致,比较多余位数
            for (int i = index; i < version1Array.length; i++) {
                if (Integer.parseInt(version1Array[i]) > 0) {
                    return 1;
                }
            }

            for (int i = index; i < version2Array.length; i++) {
                if (Integer.parseInt(version2Array[i]) > 0) {
                    return -1;
                }
            }
            return 0;
        } else {
            return diff > 0 ? 1 : -1;
        }
    }

    




    

    /**
     * Bitmap转换成byte[]并且进行压缩,压缩到不大于maxkb
     *
     * @param bitmap
     * @param
     * @return
     */
    public static byte[] bitmapBytes(Bitmap bitmap, int maxkb) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, output);
        int options = 100;
        while (output.toByteArray().length > maxkb && options != 10) {
            output.reset(); //清空output
            bitmap.compress(Bitmap.CompressFormat.JPEG, options, output);//这里压缩options%,把压缩后的数据存放到output中
            options -= 10;
        }
        return output.toByteArray();
    }

    /**
     * 按质量压缩图片 * * @param src bitmap图片 * @param maxByteSize 最大字节数 * @param recycle * @return
     */
    public static byte[] compressByQuality(final Bitmap src, final long maxByteSize, final boolean recycle) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        src.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] bytes;
        if (baos.size() <= maxByteSize) {
            bytes = baos.toByteArray();
        } else {
            baos.reset();
            src.compress(Bitmap.CompressFormat.JPEG, 0, baos);
            if (baos.size() >= maxByteSize) {
                bytes = baos.toByteArray();
            } else { // find the best quality using binary search
                int st = 0;
                int end = 100;
                int mid = 0;
                while (st < end) {
                    mid = (st + end) / 2;
                    baos.reset();
                    src.compress(Bitmap.CompressFormat.JPEG, mid, baos);
                    int len = baos.size();
                    if (len == maxByteSize) {
                        break;
                    } else if (len > maxByteSize) {
                        end = mid - 1;
                    } else {
                        st = mid + 1;
                    }
                }
                if (end == mid - 1) {
                    baos.reset();
                    src.compress(Bitmap.CompressFormat.JPEG, st, baos);
                }
                bytes = baos.toByteArray();
            }
        }
        if (recycle && !src.isRecycled()) src.recycle();
        return bytes;
    }

    // 获取地址信息
    public static List<Address> getAddress(Location location, Context mContext) {
        //用来接收位置的详细信息
        List<Address> result = null;
        try {
            if (location != null) {
                Geocoder gc = new Geocoder(mContext, Locale.getDefault());
                result = gc.getFromLocation(location.getLatitude(),
                        location.getLongitude(), 1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }



    public static void setTextMarquee(TextView textView) {
        if (textView != null) {
            textView.setEllipsize(TextUtils.TruncateAt.MARQUEE);
            textView.setSingleLine(true);
            textView.setSelected(true);
            textView.setFocusable(true);
            textView.setFocusableInTouchMode(true);
            textView.setMarqueeRepeatLimit(-1);
        }
    }


    /**
     * 特殊字体
     */
    public static void tvPtdinType(Context context, TextView textView) {
        Typeface face = Typeface.createFromAsset(context.getAssets(), "fonts/PTDINCondensedCyrillic.ttf");
        textView.setTypeface(face);
    }


    /**
     * 获取指定文件大小
     */
    public static long getFileSize(File file) throws Exception {
        long size = 0;
        if (file.exists()) {
            FileInputStream fis = null;
            fis = new FileInputStream(file);
            size = fis.available();
        } else {
            file.createNewFile();
            Log.e("获取文件大小", "文件不存在!");
        }
        return size;
    }

    /**
     * 转换文件大小
     *
     * @param fileS
     * @return
     */
    public static String formetFileSize(long fileS) {
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        String wrongSize = "0B";
        if (fileS == 0) {
            return wrongSize;
        }
        if (fileS < 1024) {
            fileSizeString = df.format((double) fileS) + "B";
        } else if (fileS < 1048576) {
            fileSizeString = df.format((double) fileS / 1024) + "KB";
        } else if (fileS < 1073741824) {
            fileSizeString = df.format((double) fileS / 1048576) + "MB";
        } else {
            fileSizeString = df.format((double) fileS / 1073741824) + "GB";
        }
        return fileSizeString;
    }

    /**
     * 获取屏幕的宽高
     *
     * @param window
     */
    public static Integer[] getWindowWH(Window window) {
        DisplayMetrics outMetrics = new DisplayMetrics();
        window.getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
        Integer[] p = {outMetrics.widthPixels, outMetrics.heightPixels};
        return p;
    }


    public static Bitmap getBitmapFromFile(String filePath) {
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inScaled = true;
        opts.inDensity = 320;
        return BitmapFactory.decodeFile(filePath, opts);
    }


    public static String formatDouble2(double d) {
        NumberFormat nf = NumberFormat.getNumberInstance();
        nf.setMaximumFractionDigits(10);
        return nf.format(d);
    }

    public static String formatDouble2Decimal(double d) {
        NumberFormat nf = NumberFormat.getNumberInstance();
        nf.setMaximumFractionDigits(2);
        return nf.format(d);
    }

    public static String formatDouble8Decimal(double d) {
        NumberFormat nf = NumberFormat.getNumberInstance();
        nf.setMaximumFractionDigits(8);
        return nf.format(d);
    }

    public static String formatDouble3(double d) {
        NumberFormat nf = NumberFormat.getNumberInstance();
        // 保留两位小数
        nf.setMaximumFractionDigits(2);
        // 如果不需要四舍五入,可以使用RoundingMode.DOWN
        nf.setRoundingMode(RoundingMode.HALF_UP);
        return nf.format(d);
    }


    /**
     * 关闭键盘
     */
    public static void closeKeyboard(Context context, View v) {
        InputMethodManager mgr = (InputMethodManager) context.getSystemService(INPUT_METHOD_SERVICE);
        mgr.hideSoftInputFromWindow(v.getWindowToken(), 0); // 0 force close IME
//        v.clearFocus();
    }


    //读取指定目录下的所有TXT文件的文件内容
    public static String getTxtFileContent(File file) {
        String content = "";
        if (!file.isDirectory()) {  //检查此路径名的文件是否是一个目录(文件夹)
            if (file.getName().endsWith("txt")) {//文件格式为""文件
                try {
                    InputStream instream = new FileInputStream(file);
                    if (instream != null) {
                        InputStreamReader inputreader
                                = new InputStreamReader(instream, "UTF-8");
                        BufferedReader buffreader = new BufferedReader(inputreader);
                        String line = "";
                        //分行读取
                        while ((line = buffreader.readLine()) != null) {
                            content += line + "\n";
                        }
                        instream.close();//关闭输入流
                    }
                } catch (FileNotFoundException e) {
                    Log.d("TestFile", "The File doesn't not exist.");
                } catch (IOException e) {
                    Log.d("TestFile", e.getMessage());
                }
            }
        }
        return content;
    }

    /**
     * 获取手机设备信息
     *
     * @return
     */
    public static String getMobileInfo() {
        String info = "";
        try {
            info = "手机设备名:" + Build.BRAND + "\n手机型号:" + Build.MODEL +
                    "\nAndroid版本:" + Build.VERSION.RELEASE;
        } catch (Exception e) {
            info = "获取信息失败";
        }
        Log.i("gao", "log mobile info==>" + info);
        return info;
    }

    public static String getAmountStr(String numStr) {
        if (TextUtils.isEmpty(numStr)) {
            return "0";
        }
        double dou = Double.parseDouble(numStr);
        String needStr = (int) dou + "";
        if (dou / 10000 >= 1) {
            if (dou / 100000000 >= 1) {
                if (dou % 100000000 == 0) {
                    needStr = (int) (dou / 100000000) + "亿";
                } else {
                    needStr = dou / 100000000 + "亿";
                }
            } else if (dou / 10000000 >= 1) {
                if (dou % 10000000 == 0) {
                    needStr = (int) (dou / 10000000) + "千万";
                } else {
                    needStr = dou / 10000000 + "千万";
                }
            } else if (dou % 10000 == 0) {
                needStr = (int) (dou / 10000) + "万";
            } else {
                needStr = dou / 10000 + "万";
            }
        }
        return needStr;
    }

    /**
     * 获取控件的高度或者宽度  isHeight=true则为测量该控件的高度,isHeight=false则为测量该控件的宽度
     *
     * @param view
     * @param isHeight
     * @return
     */
    public static int getViewHeight(View view, boolean isHeight) {
        int result;
        if (view == null) return 0;
        if (isHeight) {
            int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
            view.measure(h, 0);
            result = view.getMeasuredHeight();
        } else {
            int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
            view.measure(0, w);
            result = view.getMeasuredWidth();
        }
        return result;
    }


    private Bitmap getViewBitmap(View v) {
        v.clearFocus();
        v.setPressed(false);
        boolean willNotCache = v.willNotCacheDrawing();
        v.setWillNotCacheDrawing(false);
        int color = v.getDrawingCacheBackgroundColor();
        v.setDrawingCacheBackgroundColor(0);
        if (color != 0) {
            v.destroyDrawingCache();
        }
        v.buildDrawingCache();
        Bitmap cacheBitmap = v.getDrawingCache();
        if (cacheBitmap == null) {
            return null;
        }
        Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);
        v.destroyDrawingCache();
        v.setWillNotCacheDrawing(willNotCache);
        v.setDrawingCacheBackgroundColor(color);
        return bitmap;
    }

   

    //设置画笔的字体和颜色
    public static TextPaint myTextPaint(Context context) {
        TextPaint textPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG);// 设置画笔
        textPaint.setTextSize(sp2px(context, 9));// 字体大小
        textPaint.setTypeface(Typeface.DEFAULT_BOLD);// 采用默认的宽度
        textPaint.setColor(Color.WHITE);// 采用的颜色
        return textPaint;
    }

    //写入文字,自动换行的方法
    public static void drawText(Canvas canvas, TextPaint Paint, String textString, int x, int y, int width) {
        //int Width=Math.round(width* getRATIO());
        int start_x = Math.round(x);
        int start_y = Math.round(y);
        StaticLayout staticLayout = new StaticLayout(textString, Paint, width,
                Layout.Alignment.ALIGN_CENTER, 1f, 0.0f, false);
        //绘制的位置
        canvas.translate(start_x, start_y);
        staticLayout.draw(canvas);
    }

    public static int sp2px(Context context, float spValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

  
}

相关标签: android android