为了账号安全,请及时绑定邮箱和手机立即绑定

Android 缩放图片的几种方式说明

标签:
Android

1. BitmapFactory.Options
options.inSampleSize,它的取值应该是2的次方:1、2、4、8...
表示宽高都是原来的1/1, 1/2, 1/4, 1/8...
如果设置的值 < 1,那么效果就和 =1是一样的
再调用BitmapFactory的相关decode方法,传入options参数,即可得到一张缩小后的图片。
附上一段计算inSampleSize的方法:

static int calculateInSampleSize(BitmapFactory.Options options,
            int reqWidth, int reqHeight) {
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;
        if (height > reqHeight  width > reqWidth) {
            final int halfHeight = height / 2;
            final int halfWidth = width / 2;
            while ((halfHeight / inSampleSize) > reqHeight
                    && (halfWidth / inSampleSize) > reqWidth) {
                inSampleSize *= 2;
            }
        }
        return inSampleSize; 
}

2. Bitmap.createBitmap(Bitmap source, int x, int y, int width, int height, Matrix m, boolean filter)
以source的x,y为起点,宽w高h的范围,进行matrix变化。
这里只讨论缩放,那么matrix肯定是添加了scale操作。
要注意的是这里的参数x、y、width、height都是相对于source原图的。
如果x=y=0; w=source.getWidth()/2, h=source.getHeight()/2;scale=2;
那么最后的效果,只是取原图的左上四分之一的部份...并对这部份进行2倍放大


3. Bitmap.createScaledBitmap(bitmap, w, h, boolean filter);
以w,h为目标对bitmap进行缩放,filter表示是否要对位图进行过滤(滤波)处理
这个方法的效果就类似于ImageView.ScaleType.FIT_XY

4. canvas.drawBitmap(bitmap, matrix, paint);
postScale(float sx, float sy);
postScale(float sx, float sy, float px, float py);
preScale(float sx, float sy);
preScale(float sx, float sy, float px, float py);
pre 表示原矩阵右乘 M' = M S(sx, sy, px, py)
post 左乘 M' = S(sx, sy)
M
只有两个参数的,它的默认缩放对称点是(0, 0)
(px, py) 就是指定缩放的对称点
如:matrix.postScale(1f, 1);
图片描述

如:matrix.postScale(0.5f, 1);
图片描述

如:matrix.postScale(0.5f, 1, foreImage.getWidth()/2, 0);
图片描述

如果缩放的值为负数,
x为负:图片水平镜像(类似相机自拍,看得是左边角度,拍出来是右边),
再平移-(图宽-对称点x);
y为负:图片垂直镜像(类似水中倒影),
再平移-(图高-对称点y);
matrix.postScale(-1, 1); 默认以(0,0)点为对称点,再平移-bitmapWidth,这时就看不到图了。
所以后面要跟 matrix.postTranslate(bitmapWidth, 0); 就能看到完整图了

关于Bitmap.createBitmap(...matrix...) 这个方法内部作了平移的操作,所以我们只管传缩放值,就能生成期望的图片

点击查看更多内容
2人点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
移动开发工程师
手记
粉丝
10
获赞与收藏
106

关注作者,订阅最新文章

阅读免费教程

感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消