#跟着晓明学鸿蒙# GridRow组件实现响应式图片画廊布局
·

目录
- 案例介绍
- 代码实现
- 1. 定义数据模型
- 2. 创建主页面组件
- 代码详解
- 1. 响应式布局实现
- 2. 图片展示实现
- 总结
案例介绍
本篇文章将介绍如何使用GridRow组件创建一个响应式的图片画廊布局。通过GridRow组件的灵活布局能力,我们可以根据屏幕尺寸自动调整每行显示的图片数量,为用户提供良好的浏览体验。
代码实现
1. 定义数据模型
interface ImageItem {
id: number;
url: string;
title: string;
description: string;
}
2. 创建主页面组件
@Entry
@Component
struct ImageGalleryPage {
// 图片数据
@State imageList: ImageItem[] = [
{ id: 1, url: 'https://example.com/image1.jpg', title: '风景照片1', description: '美丽的山水风景' },
{ id: 2, url: 'https://example.com/image2.jpg', title: '风景照片2', description: '宁静的湖泊' },
// ... 更多图片数据
];
// 当前窗口宽度
@State windowWidth: number = 0;
aboutToAppear() {
// 获取窗口宽度
this.windowWidth = AppStorage.Get('windowWidth') || 360;
}
build() {
Column() {
// 标题栏
Row() {
Text('图片画廊').fontSize(24).fontWeight(FontWeight.Bold)
}
.width('100%')
.padding({ top: 16, bottom: 16 })
// 图片网格
GridRow({
// 根据窗口宽度动态调整列数
columns: this.windowWidth <= 600 ? 2 : (this.windowWidth <= 840 ? 3 : 4),
gutter: 16
}) {
ForEach(this.imageList, (item: ImageItem) => {
GridItem() {
Column() {
// 图片容器
Stack({ alignContent: Alignment.BottomStart }) {
// 图片
Image(item.url)
.objectFit(ImageFit.Cover)
.width('100%')
.aspectRatio(1)
.borderRadius(8)
// 图片标题背景
Column()
.width('100%')
.height('30%')
.linearGradient({
angle: 90,
colors: [['rgba(0,0,0,0)', 0], ['rgba(0,0,0,0.7)', 1]]
})
// 图片标题
Text(item.title)
.fontSize(16)
.fontColor(Color.White)
.padding(8)
}
.width('100%')
.borderRadius(8)
}
.width('100%')
}
})
}
.width('100%')
.padding(16)
}
.width('100%')
}
}
代码详解
1. 响应式布局实现
GridRow({
columns: this.windowWidth <= 600 ? 2 : (this.windowWidth <= 840 ? 3 : 4),
gutter: 16
})
这段代码是实现响应式布局的核心。通过监听窗口宽度,动态调整GridRow的columns属性:
- 窗口宽度 ≤ 600px:显示2列
- 600px < 窗口宽度 ≤ 840px:显示3列
- 窗口宽度 > 840px:显示4列
2. 图片展示实现
Stack({ alignContent: Alignment.BottomStart }) {
Image(item.url)
.objectFit(ImageFit.Cover)
.width('100%')
.aspectRatio(1)
.borderRadius(8)
Column()
.width('100%')
.height('30%')
.linearGradient({
angle: 90,
colors: [['rgba(0,0,0,0)', 0], ['rgba(0,0,0,0.7)', 1]]
})
Text(item.title)
.fontSize(16)
.fontColor(Color.White)
.padding(8)
}
图片展示采用Stack布局,包含三个层次:
- 图片层:使用aspectRatio(1)保持1:1的宽高比
- 渐变背景层:使用linearGradient创建从透明到半透明黑色的渐变效果
- 标题层:在渐变背景上显示白色标题文本
总结
本篇文章展示了如何使用GridRow组件创建响应式图片画廊布局。通过GridRow的columns属性实现了根据屏幕宽度自动调整列数的功能,结合Stack布局创建了美观的图片卡片效果。这种布局方式不仅能够适应不同屏幕尺寸,还能为用户提供统一的视觉体验。
更多推荐


所有评论(0)