回复
#我的鸿蒙开发手记#鸿蒙开发:ArkTs中图片与视频的使用 原创
Mi3sy
发布于 2025-5-8 15:02
浏览
0收藏
在ArkTS中,图片和视频的使用主要通过组件和资源管理实现
图片使用
- 资源类型
本地图片:存放在resources目录下的base/media或rawfile文件夹。
网络图片:直接使用图片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组件
// 加载本地图片
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)
- 关键属性
objectFit:控制图片填充方式(Cover填充,Contain适应等)。
interpolation:图片插值效果(清晰度优化)。
alt:加载失败时的占位图(需通过$r引用本地资源)。
视频使用
- Video组件
// 播放本地视频
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('视频加载失败');
})
- 视频控制
通过VideoController控制播放状态:
// 定义控制器
private videoController: VideoController = new VideoController();
// 播放/暂停
this.videoController.start();
this.videoController.pause();
// 跳转到指定位置(单位:秒)
this.videoController.setCurrentTime(10);
// 全屏播放
this.videoController.requestFullscreen(true);
- 关键属性
controls:是否显示默认控制条。
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中实现图片和视频的加载与控制。
©著作权归作者所有,如需转载,请注明出处,否则将追究法律责任
标签
已于2025-5-9 12:05:40修改
赞
收藏
回复
相关推荐



















