前言
Image
通過調(diào)用接口來創(chuàng)建难咕,接口調(diào)用形式如下:
Image(src: string | Resource | media.PixelMap)
該接口通過圖片數(shù)據(jù)源獲取圖片苇经,支持本地圖片和網(wǎng)絡(luò)圖片的渲染展示。其中座韵,src
是圖片的數(shù)據(jù)源。
加載圖片資源
Image
支持加載存檔圖(重點)踢京、多媒體像素圖(了解即可)兩種類型回右。
存檔圖類型數(shù)據(jù)源
存檔圖類型的數(shù)據(jù)源可以分為本地資源、網(wǎng)絡(luò)資源漱挚、Resource
資源翔烁、媒體庫資源和base64
。
- 本地資源
創(chuàng)建文件夾旨涝,將本地圖片放入ets
文件夾下的任意位置蹬屹。
Image
組件引入本地圖片路徑,即可顯示圖片(根目錄為ets
文件夾)白华。
Image('images/view.jpg')
.width(200)
- 網(wǎng)絡(luò)資源
引入網(wǎng)絡(luò)圖片需申請權(quán)限ohos.permission.INTERNET
慨默,具體申請方式請參考權(quán)限申請聲明。此時弧腥,Image
組件的src
參數(shù)為網(wǎng)絡(luò)圖片的鏈接厦取。
Image('https://www.example.com/example.JPG') // 實際使用時請?zhí)鎿Q為真實地址
- Resource資源
使用資源格式可以跨包/跨模塊引入圖片,resources
文件夾下的圖片都可以通過$r
資源接口讀取到并轉(zhuǎn)換到Resource
格式管搪。
調(diào)用方式:
Image($r('app.media.icon'))
還可以將圖片放在rawfile
文件夾下虾攻。
調(diào)用方式:
Image($rawfile('snap'))
- 媒體庫
file://data/storage
支持file://
路徑前綴的字符串铡买,用于訪問通過媒體庫提供的圖片路徑。
a
. 調(diào)用接口獲取圖庫的照片url
霎箍。
import picker from '@ohos.file.picker';
@Entry
@Component
struct Index {
@State imgDatas: string[] = [];
// 獲取照片url集
getAllImg() {
let result = new Array<string>();
try {
let PhotoSelectOptions = new picker.PhotoSelectOptions();
PhotoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE;
PhotoSelectOptions.maxSelectNumber = 5;
let photoPicker = new picker.PhotoViewPicker();
photoPicker.select(PhotoSelectOptions).then((PhotoSelectResult) => {
this.imgDatas = PhotoSelectResult.photoUris;
console.info('PhotoViewPicker.select successfully, PhotoSelectResult uri: ' + JSON.stringify(PhotoSelectResult));
}).catch((err) => {
console.error(`PhotoViewPicker.select failed with. Code: ${err.code}, message: ${err.message}`);
});
} catch (err) {
console.error(`PhotoViewPicker failed with. Code: ${err.code}, message: ${err.message}`); }
}
// aboutToAppear中調(diào)用上述函數(shù)奇钞,獲取圖庫的所有圖片url,存在imgDatas中
async aboutToAppear() {
this.getAllImg();
}
// 使用imgDatas的url加載圖片漂坏。
build() {
Column() {
Grid() {
ForEach(this.imgDatas, item => {
GridItem() {
Image(item)
.width(200)
}
}, item => JSON.stringify(item))
}
}.width('100%').height('100%')
}
}
b
. 從媒體庫獲取的url
格式通常如下景埃。
Image('file://media/Photos/5')
.width(200)
- base64
路徑格式為data:image/[png|jpeg|bmp|webp];base64,[base64 data]
,其中[base64 data]
為Base64
字符串?dāng)?shù)據(jù)顶别。
Base64
格式字符串可用于存儲圖片的像素數(shù)據(jù)谷徙,在網(wǎng)頁上使用較為廣泛。