gpt4 book ai didi

android - 在 Android 启动 Activity 中为 windowBackground 保持正确的纵横比

转载 作者:行者123 更新时间:2023-12-05 07:21:26 30 4
gpt4 key购买 nike

我正在努力在我的项目中实现启动 Activity 。当前启动 Activity 完美加载,并且在图像加载之前没有“白色闪光”——这很好。

我唯一的问题是保持初始屏幕图像的正确纵横比

这是我为 SplashActivity 使用的主题

<style name="SplashTheme" parent="Theme.AppCompat.NoActionBar">
<item name="android:windowBackground">@drawable/splash</item>
</style>

splash.xml

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

这是我得到的结果的屏幕截图:

Improper Aspect Ratio

我用作背景的黑色/粉红色网格图像具有统一的正方形。正如您从图像中看到的那样,它没有保持适当的纵横比(被水平挤压)。

这是网格图像 (1280x1920):

Pink and black grid image

我尝试了什么:

似乎控制启动窗口背景的纵横比的唯一方法是使用gravity。我试图垂直填充图像并水平裁剪。但这并不能保持宽高比。

如何调整启动图像的重力以保持纵横比并适合任何设备的屏幕?

编辑:基于 Raz 的回答的进度:

activity_splash.xml

<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/pink_grid" android:scaleType="centerCrop"/>
</merge>

SplashActivity.kt

class SplashActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_splash)

// val intent = Intent(this, MainActivity::class.java)
// startActivity(intent)
// finish()
}
}

AndroidManifest.xml

<application>
<!-- ... -->
<activity
android:name=".SplashActivity"
android:theme="@style/SplashTheme">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>

样式.xml

<style name="SplashTheme" parent="Theme.AppCompat.NoActionBar">
<item name="android:windowBackground">@android:color/transparent</item>
</style>

启动画面现在只是黑屏。粉色/黑色网格未显示。

最佳答案

据我所知,windowBackground 将始终填满屏幕。你需要做的是:

将 Activity 的布局设置为:

<FrameLayout 
android:width="match_parent"
android:height="match_parent">
<ImageView
android:width="match_parent"
android:height="match_parent"
android:ScaleType="CENTER_CROP" android:src="your_image"/>
</FrameLayout>

imageView 属性 scaletype 将保留纵横比。

作为优化:

  1. 将 windowBackground 设置为透明(以减少 overdraw )
  2. 将根 FrameLayout 更改为 <merge> - 像这样:

<merge>
<ImageView<br/>
android:width="match_parent"<br/>
android:height="match_parent"<br/>
android:ScaleType="CENTER_CROP" android:src="your_image"/>
</merge>

关于android - 在 Android 启动 Activity 中为 windowBackground 保持正确的纵横比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56925843/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com