3. 界面布局搭建
页面布局包含头部导航栏、图片展示区域和拼接方式选择区域。头部导航栏提供返回和保存功能,图片展示区域使用 List
组件展示两张图片,拼接方式选择区域使用 SegmentButton
组件供用户选择左右拼接或上下拼接。代码如下:
build() {
NavDestination() {
Column() {
this.Header()
List() {
ListItem() {
DragListItem({ item: this.pixelItemLeft, index: this.dragIndex })
}
.height(CommonConstants.FULL_HEIGHT)
ListItem() {
DragListItem({ item: this.pixelItemRight, index: this.dragIndex })
}
.height(CommonConstants.FULL_HEIGHT)
}
.listDirection(Axis.Horizontal)
.padding(16)
.id(STITCH_AREA_ID)
.width(CommonConstants.FULL_WIDTH)
.backgroundColor(CommonConstants.BACKGROUND_COLOR)
.layoutWeight(1)
.onDrop((event: DragEvent, extraParams?: string) => {
let insertIndex = JSON.parse(extraParams as string)['insertIndex'] as number
if (this.dragIndex !== insertIndex) {
let tempPixelMap = ImageUtils.clonePixelMap(this.pixelItemRight.pixelMap as PixelMap)
this.pixelItemRight.pixelMap = ImageUtils.clonePixelMap(this.pixelItemLeft.pixelMap as PixelMap)
this.pixelItemLeft.pixelMap = ImageUtils.clonePixelMap(tempPixelMap)
}
})
Column() {
Row() {
SegmentButton({ options: this.tabOptions,
selectedIndexes: $tabSelectedIndexes })
.height(40)
}
}
.width(CommonConstants.FULL_WIDTH)
.padding({ left: 16, right: 16, top: 18 })
.backgroundColor(CommonConstants.BACKGROUND_COLOR_WHITE)
.height(100)
}
.height(CommonConstants.FULL_HEIGHT)
}
.hideTitleBar(true)
.padding({ bottom: 40, top: 40 })
}
4. 订单确认与图片拼接
点击保存按钮时,调用 confirmOrder
函数。该函数会对两张图片进行裁剪,使它们的高度一致,然后调用 joinImages
函数进行拼接,最后将拼接后的图片保存到 AppStorage
中,并跳转到订单页面。代码如下:
async confirmOrder() {
try {
if (!this.pixelItemLeft.pixelMap || !this.pixelItemRight.pixelMap) {
return
}
if (this.leftInfo.size.height >= this.rightInfo.size.height) {
let cropY = (this.leftInfo.size.height - this.rightInfo.size.height) / 2
await cropImage(this.pixelItemLeft.pixelMap, 0, cropY, this.leftInfo.size.width, this.rightInfo.size.height)
} else {
let cropY = (this.rightInfo.size.height - this.leftInfo.size.height) / 2
await cropImage(this.pixelItemRight.pixelMap, 0, cropY, this.rightInfo.size.width, this.leftInfo.size.height)
}
let pixel = await joinImages([this.pixelItemLeft.pixelMap, this.pixelItemRight.pixelMap])
AppStorage.setOrCreate('orderImage', pixel)
this.pageRouter.pushPathByName(RouteMap.ORDER_PAGE, '')
} catch (e) {
Logger.debug('stitch error', JSON.stringify(e))
}
}
通过以上代码,开发者可以在HarmonyOS Next应用中实现一个完整的图片拼图功能,包括图片加载、缩放、布局展示、拼接方式选择和图片拼接等核心功能。