【问题标题】:Changing bitmap dimensions without modifying aspect ratio在不修改纵横比的情况下更改位图尺寸
【发布时间】:2012-09-03 13:26:58
【问题描述】:

有什么方法可以增加位图的宽度(或高度)而不拉伸它?基本上,我有一个 200x100 的位图,我想通过在左侧附加 50 个(白色/透明)像素和在右侧附加 50 个像素来使其成为正方形(200x200)。

我不想在屏幕上绘制此位图,因此,理想情况下,我应该以“智能”方式或类似方式使用转换矩阵,但我就是想不通...

【问题讨论】:

    标签: android bitmap image-resizing


    【解决方案1】:

    你可以试试这样的:

            // creating a dummy bitmap
            Bitmap source = Bitmap.createBitmap(100, 200, Bitmap.Config.ARGB_8888);
            Bitmap background;
            Canvas canvas;
    
            if(source.getHeight() == source.getWidth()) // do nothing
                return;
    
            // create a new Bitmap with the bigger side (to get a square)
            if(source.getHeight() > source.getWidth()) {
                background = Bitmap.createBitmap(source.getHeight(), source.getHeight(), Bitmap.Config.ARGB_8888);
                canvas = new Canvas(background);
                // draw the source image centered
                canvas.drawBitmap(source, source.getHeight()/4, 0, new Paint());
            } else {
                background = Bitmap.createBitmap(source.getWidth(), source.getWidth(), Bitmap.Config.ARGB_8888);
                canvas = new Canvas(background);
                // draw the source image centered
                canvas.drawBitmap(source, 0, source.getWidth()/4, new Paint());
            }
    
            source.recycle();
            canvas.setBitmap(null);
            // update the source image
            source = background;
    

    注意:黑色边框不是图像的一部分。我选择深红色作为背景颜色,以查看图像的实际大小并将其与黑色和源图像的颜色(始终居中绘制)区分开来。

    通过在画布上绘制它在屏幕上不可见。我使用 ImageView 只是为了测试代码。

    这是我得到的 w=200,h=100 的输出:

    这是我得到的 w=100,h=200 的输出:

    【讨论】:

      猜你喜欢
      • 2018-04-22
      • 2018-01-18
      • 1970-01-01
      • 1970-01-01
      • 2013-10-13
      • 1970-01-01
      • 2016-08-06
      • 2019-05-14
      • 1970-01-01
      相关资源
      最近更新 更多