【问题标题】:drawable fit <bitmap> width to the view while keeping aspect ratio可绘制适合 <bitmap> 宽度到视图,同时保持纵横比
【发布时间】:2018-07-21 12:54:40
【问题描述】:

假设我有一个水平长的图像,“草”。现在,我想将它用作视图的背景图像,但我想将它停靠在底部。在网上搜索后,我发现我需要将图像包装为可绘制对象:

<?xml version="1.0" encoding="utf-8"?>
<bitmap
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:src="@drawable/grass"
    android:gravity="bottom|left" />

问题是图像被剪裁到右侧。所以我尝试了bottom|left|right,但没有保留纵横比。我可以使图像水平适合,但通过自动垂直缩放来保持纵横比?或者这对于drawables是不可能的?

【问题讨论】:

    标签: android android-drawable


    【解决方案1】:

    您搜索的是 centerInside ScaleType 。请从 ImageView 中删除 ScaleType 并尝试以下操作:

     public static synchronized Bitmap centerInside(Bitmap bitmap,int width,int height){
        if(bitmap.getWidth() == bitmap.getHeight()){
            Log.i("crop","already matched");
            return Bitmap.createScaledBitmap(bitmap, width, height, true);
        }
        //int size = width > height ? width : height;
    
        float scale = ImageUtils.calculateImageSampleSize(bitmap.getWidth(), bitmap.getHeight(),width,height);
        width = (int) ((float)bitmap.getWidth() / scale);
        height = (int) ((float)bitmap.getHeight() / scale);
        bitmap = Bitmap.createScaledBitmap(bitmap, width, height, true);
    
        if (bitmap.getWidth() >= bitmap.getHeight()){
    
            bitmap = Bitmap.createBitmap(
                    bitmap,
                    bitmap.getWidth()/2 - bitmap.getHeight()/2,
                    0,
                    bitmap.getHeight(),
                    bitmap.getHeight()
            );
    
        }else{
    
            bitmap = Bitmap.createBitmap(
                    bitmap,
                    0,
                    bitmap.getHeight()/2 - bitmap.getWidth()/2,
                    bitmap.getWidth(),
                    bitmap.getWidth()
            );
        }
        return bitmap;
    }
    

    【讨论】:

      【解决方案2】:

      您无法仅使用 XML 实现此目的。如果您不想以编程方式绘制位图,请将 ImageView 包装在 RelativeLayout 中并设置 ImageView 的 scaleType 属性:

      <RelativeLayout
          android:layout_width="fill_parent"
          android:layout_height="fill_parent">
      
          <ImageView
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:src="@drawable/grass"
              android:scaleType="fitXY" />
      
      </RelativeLayout>
      

      【讨论】:

        【解决方案3】:

        如果我正确理解您的要求,您的图像需要垂直拉伸并在水平范围内。

        我可以建议的一个很好的解决方案是从您的可绘制对象中创建一个 9 补丁图像,并定义图像可以拉伸的区域。 可以参考this教程。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-04-01
          • 1970-01-01
          • 2020-06-08
          • 2018-08-09
          • 1970-01-01
          相关资源
          最近更新 更多