
回复
在ArkTS中,图片和视频的使用主要通过组件和资源管理实现
图片使用
网络图片:直接使用图片URL。
加载png、gif、svg和jpg等基本类型的图片。
@Entry
@Component
struct ImageExample1 {
build() {
Column() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
Row() {
// 加载png格式图片
Image($r('app.media.ic_camera_master_ai_leaf'))
.width(110).height(110).margin(15)
.overlay('png', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
// 加载gif格式图片
Image($r('app.media.loading'))
.width(110).height(110).margin(15)
.overlay('gif', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
}
Row() {
// 加载svg格式图片
Image($r('app.media.ic_camera_master_ai_clouded'))
.width(110).height(110).margin(15)
.overlay('svg', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
// 加载jpg格式图片
Image($r('app.media.ic_public_favor_filled'))
.width(110).height(110).margin(15)
.overlay('jpg', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
}
}
}.height(320).width(360).padding({ right: 10, top: 10 })
}
}
// 加载本地图片
Image($r('app.media.local_image')) // resources/base/media/local_image.png
.width(100)
.height(100)
.objectFit(ImageFit.Cover) // 缩放模式:Cover, Contain等
// 加载网络图片
Image('https://example.com/remote_image.jpg')
.width(200)
.height(200)
.onError(() => {
console.error('图片加载失败');
})
// Base64图片
Image('data:image/png;base64,<base64-string>')
.width(100)
.height(100)
interpolation:图片插值效果(清晰度优化)。
alt:加载失败时的占位图(需通过$r引用本地资源)。
视频使用
// 播放本地视频
Video({
src: $rawfile('local_video.mp4'), // 存放在resources/rawfile
controller: this.videoController // 视频控制器
})
.width(300)
.height(200)
.controls(true) // 显示默认控制条
.autoPlay(false) // 手动播放
.onPrepared(() => {
console.info('视频准备就绪');
})
// 播放网络视频
Video({
src: 'https://example.com/remote_video.mp4',
controller: this.videoController
})
.onError(() => {
console.error('视频加载失败');
})
// 定义控制器
private videoController: VideoController = new VideoController();
// 播放/暂停
this.videoController.start();
this.videoController.pause();
// 跳转到指定位置(单位:秒)
this.videoController.setCurrentTime(10);
// 全屏播放
this.videoController.requestFullscreen(true);
loop:是否循环播放。
muted:是否静音。
currentTime:监听播放进度。
注意事项
网络权限:使用网络资源时,需在module.json5中添加权限:
"requestPermissions": [
{ "name": "ohos.permission.INTERNET" }
]
资源路径:
$r(‘app.media.xxx’):访问resources/base/media下的资源。
$rawfile(‘filename’):访问resources/rawfile下的原始文件(保留目录结构)。
性能优化:
图片压缩:避免使用过大的图片资源。
视频格式:优先使用H.264编码的MP4格式,兼容性更好。
通过上述方法,可以灵活地在ArkTS中实现图片和视频的加载与控制。