1、首先選擇一張需要的圖片,通過左側的Resource Manage選擇“+”並選擇Import Drawables 選擇一張圖片 並調整以下兩個內容 這兩個內容的作用借用谷歌官方的Android開發教程的內容: *Android 設備具有不同的屏幕尺寸(手機、平板電腦和電視等),而且這些屏幕也具有 ...
1、首先選擇一張需要的圖片,通過左側的Resource Manage選擇“+”並選擇Import Drawables
選擇一張圖片
並調整以下兩個內容
這兩個內容的作用借用谷歌官方的Android開發教程的內容:
*Android 設備具有不同的屏幕尺寸(手機、平板電腦和電視等),而且這些屏幕也具有不同的像素尺寸。也就是說,有可能一部設備的屏幕為每平方英寸 160 個像素,而另一部設備的屏幕在相同的空間內可以容納 480 個像素。如果不考慮像素密度的這些變化,系統可能會按比例縮放圖片,這可能會導致圖片模糊或占用大量記憶體空間,或者圖片大小不當。
如果所調整的圖片超出了 Android 系統可處理的圖片大小,系統會拋出記憶體不足錯誤。對於照片和背景圖片(如當前圖片 androidparty.png),應將其放在 drawable-nodpi 文件夾中,這樣會停止調整大小行為*
2、在項目中,所有資源都保存在/res目錄下,具有以下例如的結構:
MyProject/
src/
MyActivity.kt
res/
drawable/
graphic.png
mipmap/
icon.png
values/
strings.xml
在項目中,R 類是 Android 自動生成的類,其中包含了項目中所有資源的 ID。所以我們可以使用R.drawable.picture_name的方式找到圖片資源。
接下來構建組合函數GreetingImage()首先在函數中定義變數image它所對應的就是我們所需要的圖片
val image = painterResource(R.drawable.androidparty)
接著構建組合內容image
Image(
painter = image,
contentDescription = null,
contentScale = ContentScale.Crop,
alpha = 0.6F
)
這裡的實參contentDescription與Talk Back內容有關,這是一個為了使更多用戶使用我們的程式所有的一些提示,這裡我們並不需要所以設置為null
ContentScale中提供各種各樣的參數來調整圖片大小比例
alpha規定了圖片透明度
最後使用Box佈局並添加上之前的"GreetingText"函數
3、最終效果
完整代碼
package com.example.happybirthday
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.happybirthday.ui.theme.HappyBirthdayTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
HappyBirthdayTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
GreetingImage("Happy Birthday,Human")
}
}
}
}
}
@Composable
fun GreetingText(message: String, modifier: Modifier = Modifier) {
Text(
text = message,
fontSize = 100.sp,
lineHeight = 113.sp)
}
@Composable
fun GreetingImage(message: String, modifier: Modifier = Modifier) {
val image = painterResource(R.drawable.androidparty)
Box {
Image(
painter = image,
contentDescription = null,
contentScale = ContentScale.Crop,
alpha = 0.5F
)
GreetingText(
message = message,
modifier = Modifier
.fillMaxSize()
.padding(8.dp)
)
}
}
@Preview(showBackground = false)
@Composable
fun GreetingPreview() {
HappyBirthdayTheme {
GreetingImage("Happy Birthday,Human")
}
}
本文由博客一文多發平臺 OpenWrite 發佈!