【问题标题】:Android crop background安卓裁剪背景
【发布时间】:2011-10-10 13:41:47
【问题描述】:

我有一个LinearLayout,宽度设置为fill_parent,高度设置为wrap_content。现在我想给它一个来自 png 文件的背景,但是以传统方式这样做会导致 LinearLayout 调整大小以显示整个背景而不是裁剪额外的部分。

如何设置LinearLayout 的背景使其不会调整大小?

谢谢

【问题讨论】:

  • 什么是传统方式?你能把它的外观和它应该是什么样子的图片放上来吗?

标签: android background drawable crop


【解决方案1】:

似乎只有使用ImageView 并相应地设置scaleType 参数才能实现这样的目标。一个快速的解决方法是使用FrameLayout 并将ImageView 放在另一个具有透明背景的布局下。

代码:

<FrameLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="centerCrop"
        android:src="@drawable/background" />

</FrameLayout>

【讨论】:

  • 这没有提供足够的细节
  • 如何做透明背景?并且每个通知它的项目都必须具有透明的背景颜色吗?
【解决方案2】:

背景位图的默认行为是完全填充容器并在需要时增加容器的水平和垂直大小。解决方案是创建一个可绘制的位图资源并更改重力。

检查以下链接并查找可能的重力值。然后你的视图应该只引用可绘制资源,你应该没问题。

http://developer.android.com/guide/topics/resources/drawable-resource.html#Bitmap

【讨论】:

    【解决方案3】:

    我通过继承LinearLayout 并覆盖onMeasure(int,int) 回调解决了这个问题,然后更新布局XML 以使用我的新布局类型。我不能发布确切的代码,但我所做的是调用super.onMeasure(int,int) 实现并检查测量的高度是否返回为我的背景图像的确切高度。如果是这样,我会获取所有子视图的测量高度,然后计算一个新的高度值并将其传递给setMeasuredDimension(int,int)

    【讨论】:

      【解决方案4】:

      将此代码放入xml活动中,例如activity_main.xml

      <ImageView
      android:id="@+id/imageView1"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:scaleType="centerCrop"
      android:src="@drawable/image" />
      

      【讨论】:

        猜你喜欢
        • 2013-12-03
        • 1970-01-01
        • 1970-01-01
        • 2016-01-19
        • 2012-12-02
        • 2014-07-06
        • 1970-01-01
        • 2021-09-14
        • 1970-01-01
        相关资源
        最近更新 更多