android开发步步为营之111:将图片转换成指定宽和高

本文介绍如何将Bitmap图像调整到与GlSurfaceView相同的宽度和高度,提供了两种方法:一是使用Matrix进行缩放,二是利用ThumbnailUtils工具类实现。通过对源代码的解析,揭示了这两种方法的具体实现细节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//将bitmap转成和GlSurfaceView一样的宽和高
Bitmap bitmap = BitmapFactory.decodeStream(getAssets().open(fileName));
//方法一:使用Matrix
Matrix matrix=new Matrix();
matrix.postScale((float)glView.getWidth()/bitmap.getWidth(), (float)glView.getHeight()/bitmap.getHeight());
bitmap=Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(),matrix,true);
//方法二:使用系统自动的工具类 add in api 8
bitmap= ThumbnailUtils.extractThumbnail(bitmap, glView.getWidth(), glView.getHeight());


查看方法二的源代码

    /**
     * Creates a centered bitmap of the desired size.
     *
     * @param source original bitmap source
     * @param width targeted width
     * @param height targeted height
     * @param options options used during thumbnail extraction
     */
    public static Bitmap extractThumbnail(
            Bitmap source, int width, int height, int options) {
        if (source == null) {
            return null;
        }

        float scale;
        if (source.getWidth() < source.getHeight()) {
            scale = width / (float) source.getWidth();
        } else {
            scale = height / (float) source.getHeight();
        }
        Matrix matrix = new Matrix();
        matrix.setScale(scale, scale);
        Bitmap thumbnail = transform(matrix, source, width, height,
                OPTIONS_SCALE_UP | options);
        return thumbnail;
    }
        Bitmap b1;
        if (scaler != null) {
            // this is used for minithumb and crop, so we want to filter here.
            b1 = Bitmap.createBitmap(source, 0, 0,
            source.getWidth(), source.getHeight(), scaler, true);
        } else {
            b1 = source;
        }

发现其实还是按照方法一来实现的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值