【问题标题】:Centering a background image in Android在Android中居中背景图像
【发布时间】:2011-04-20 08:45:01
【问题描述】:

我有一个大约 100 x 100 的背景图片,我想在 Android 应用程序中居中。有没有办法做到这一点?

我认为这将对简单应用的方向更改有很大帮助。

【问题讨论】:

    标签: android background orientation center


    【解决方案1】:

    您可以使用 BitmapDrawable 的情况。在res/drawable文件夹中创建centered.xml:

    <bitmap xmlns:android="http://schemas.android.com/apk/res/android"
        android:src="@drawable/your_image"
        android:gravity="center"/>
    

    然后你可以使用centereddrawable作为背景。

    【讨论】:

      【解决方案2】:

      或者如果你想使用你的mipmap图像,你应该使用item而不是bitmap

      <?xml version="1.0" encoding="utf-8"?>
      <layer-list xmlns:android="http://schemas.android.com/apk/res/android">
          <item android:drawable="@color/app_bg_color" />
          <item android:drawable="@mipmap/ic_launcher_round"
          android:gravity="center"/>
      </layer-list>
      

      【讨论】:

        【解决方案3】:

        问题很老,答案有一个很大的弱点——我们无法更改图像大小,这意味着它完全取决于我们拥有的可绘制对象。

        虽然使用最新的 Android 设计库,活动视图的根将是 CoordinatorLayoutDrawerLayout,并且这些布局没有显示层次结构的默认视图,这意味着第一个子视图将被下一个子视图所掩盖,第二个子视图第三和...到最后一个。所以要有居中的背景我们需要添加作为第一个孩子LinearLayout,里面有居中的图像。部分代码sn-p:

        <android.support.v4.widget.DrawerLayout>
        <!-- first child -->
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center"
            >
            <ImageView
                android:layout_width="match_parent"
                android:layout_height="60dp"
                android:src="@drawable/some_background"
                />
        </LinearLayout> 
        ... next view will be above
        

        我们可以完全自定义以LinearLayout 重力选项为中心的图像大小。重要的是在 LinearLayout 的宽度和高度上设置 ma​​tch_parent,感谢该中心也将是父视图的中心。

        同样的事情可以在RelativeLayout 或任何其他允许子视图重叠的布局中完成。

        【讨论】:

          【解决方案4】:

          使用 ConstraintLayout,您可以直接设置 background 标签。老实说,我花了几个小时来解决这个问题,但它比你想象的要简单得多;)

          【讨论】:

            猜你喜欢
            • 2016-01-23
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2020-01-22
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多