美文网首页
Android Bitmap 按宽高比例居中裁剪图片大小

Android Bitmap 按宽高比例居中裁剪图片大小

作者: 星邪Ara | 来源:发表于2022-06-20 14:52 被阅读0次
     /**
         * 按照指定的4:3比例,对源Bitmap进行裁剪
         *
         * @param srcBitmap 源图片对应的Bitmap
         * @return Bitmap
         */
        public static Bitmap centerCrop4To3(Bitmap srcBitmap) {
            int desWidth = srcBitmap.getWidth();
            int desHeight = srcBitmap.getHeight();
            float desRate = (float) desWidth / desHeight;
            float rate = 4f / 3f;
            if (desRate > rate) {//宽有多余
                desWidth = (int) (desHeight * 4 / 3);
            } else {//宽有不够,裁剪高度
                desHeight = (int) (desWidth * 3 / 4);
            }
            return centerCrop(srcBitmap, desWidth, desHeight);
        }
    
        /**
         * 按照指定的6:9比例,对源Bitmap进行裁剪
         *
         * @param srcBitmap 源图片对应的Bitmap
         * @return Bitmap
         */
        public static Bitmap centerCrop16To9(Bitmap srcBitmap) {
            int desWidth = srcBitmap.getWidth();
            int desHeight = srcBitmap.getHeight();
            float desRate = (float) desWidth / desHeight;
            float rate = 16f / 9f;
            if (desRate > rate) {//宽有多余
                desWidth = (int) (desHeight * 16 / 9);
            } else {//宽有不够,裁剪高度
                desHeight = (int) (desWidth * 9 / 16);
            }
            return centerCrop(srcBitmap, desWidth, desHeight);
        }
    
        /**
         * 按照指定的宽高比例,对源Bitmap进行裁剪
         * 注意,输出的Bitmap只是宽高比与指定宽高比相同,大小未必相同
         *
         * @param srcBitmap 源图片对应的Bitmap
         * @param desWidth  目标图片宽度
         * @param desHeight 目标图片高度
         * @return Bitmap
         */
        public static Bitmap centerCrop(Bitmap srcBitmap, int desWidth, int desHeight) {
            int srcWidth = srcBitmap.getWidth();
            int srcHeight = srcBitmap.getHeight();
            int newWidth = srcWidth;
            int newHeight = srcHeight;
            float srcRate = (float) srcWidth / srcHeight;
            float desRate = (float) desWidth / desHeight;
            int dx = 0, dy = 0;
            if (srcRate == desRate) {
                return srcBitmap;
            } else if (srcRate > desRate) {
                newWidth = (int) (srcHeight * desRate);
                dx = (srcWidth - newWidth) / 2;
            } else {
                newHeight = (int) (srcWidth / desRate);
                dy = (srcHeight - newHeight) / 2;
            }
            //创建目标Bitmap,并用选取的区域来绘制
            Bitmap desBitmap = Bitmap.createBitmap(srcBitmap, dx, dy, newWidth, newHeight);
            return desBitmap;
        }
    

    相关文章

      网友评论

          本文标题:Android Bitmap 按宽高比例居中裁剪图片大小

          本文链接:https://www.haomeiwen.com/subject/aorjvrtx.html