【问题标题】:image stretches on setting as Background to GridLayout图像在设置为 GridLayout 的背景时拉伸
【发布时间】:2014-10-30 07:02:40
【问题描述】:

我有一个场景,我需要将位图设置为 gridLayout 的背景。 我使用了以下代码:

Drawable drawable = new BitmapDrawable(context.getResources(), bitmap);
bgView.setBackgroundDrawable(drawable ); 

其中 bgView 是 GridLayout 位图是我从远程服务器接收到的位图。

上面将图像设置为背景,但它会拉伸。 我需要图像在背景中居中。 谁能帮我整理一下如何将背景图像居中的问题。

【问题讨论】:

    标签: android layout


    【解决方案1】:

    前段时间,我也有同样的情况。
    我通过将ImageView 作为背景解决了这个问题。
    它看起来像这样:

    grid_item.xml

    <FrameLayout>
    
      <!-- wrap original with FrameLayout then put ImageView as bg! -->
      <ImageView />
    
      <OriginalLayout>
        ...
      <OriginalLayout>
    
    </FrameLayout>
    

    如果OriginalLayoutFrameLayoutRelativeLayout 或类似的,
    你不必用FrameLayout包装

    希望它提示您解决。

    【讨论】:

      【解决方案2】:

      您必须创建另一个位图,该位图可以填充您的网格布局而无需拉伸。就个人而言,我更喜欢通过在画布中填充(通过缩放)来填充完整的背景,然后进一步裁剪它,也称为中心裁剪。我找到了这段代码:

      public Bitmap scaleCenterCrop(Bitmap source, int newHeight, int newWidth) {
          int sourceWidth = source.getWidth();
          int sourceHeight = source.getHeight();
      
          // Compute the scaling factors to fit the new height and width, respectively.
          // To cover the final image, the final scaling will be the bigger 
          // of these two.
          float xScale = (float) newWidth / sourceWidth;
          float yScale = (float) newHeight / sourceHeight;
          float scale = Math.max(xScale, yScale);
      
          // Now get the size of the source bitmap when scaled
          float scaledWidth = scale * sourceWidth;
          float scaledHeight = scale * sourceHeight;
      
          // Let's find out the upper left coordinates if the scaled bitmap
          // should be centered in the new size give by the parameters
          float left = (newWidth - scaledWidth) / 2;
          float top = (newHeight - scaledHeight) / 2;
      
          // The target rectangle for the new, scaled version of the source bitmap will now
          // be
          RectF targetRect = new RectF(left, top, left + scaledWidth, top + scaledHeight);
      
          // Finally, we create a new bitmap of the specified size and draw our new,
          // scaled bitmap onto it.
          Bitmap dest = Bitmap.createBitmap(newWidth, newHeight, source.getConfig());
          Canvas canvas = new Canvas(dest);
          canvas.drawBitmap(source, null, targetRect, null);
      
          return dest;
      }
      

      用法:从远程服务器获取位图(Ist 参数),网格布局的宽度和高度(IInd 和 IIIrd 参数),并使用返回的位图作为网格布局的背景。

      希望它会有所帮助。 (PS:它不会增加您的视图层次结构,否则另一种解决方案是在网格后面获取图像视图并设置其比例类型 centerCrop 并在其中设置背景图像)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-06-06
        • 2012-09-19
        • 2010-11-09
        • 2011-11-12
        • 2012-01-02
        • 2016-04-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多