前往小程序,Get更优阅读体验!
立即前往
发布
社区首页 >专栏 >HarmonyOS 开发实践 —— 基于ArkUI实现类似.9图的拉伸能力

HarmonyOS 开发实践 —— 基于ArkUI实现类似.9图的拉伸能力

原创
作者头像
小帅聊鸿蒙
发布2024-12-04 20:49:44
发布2024-12-04 20:49:44
1030
举报
文章被收录于专栏:鸿蒙开发笔记鸿蒙开发笔记

场景描述

应用聊天界面简单气泡的拉伸实现。

效果图

最上方是未被拉伸的气泡图效果。

方案描述

分别使用backgroundImageResizable和resizable实现聊天气泡的拉伸。

backgroundImageResizable和resizable使用详解。

文档提供的图片,在设置了top、right、bottom、left四个参数后,图上的4角也就是1234区域不会被拉伸,关键点在于这4个参数的大小必须是原图的基础上的大小,所以需要将原图像素值转为vp后,在此基础上来确认参数。

效果图

核心代码 

代码语言:ts
复制
// bubble3 宽472px高200px
@State w: number = px2vp(472)
@State h: number = px2vp(200)
......
Stack() {
  Image($r('app.media.bubble3'))
    .width(this.w)
    .height(this.h)
    .borderRadius(4)
    .resizable({
      slice: {
        top: this.top,
        bottom: this.bottom,
        left: this.left,
        right: this.right
      }
    })
    .objectFit(this.fit)
  Divider().strokeWidth(1).color(Color.Red)
    .position({ top: this.top })
  Divider().strokeWidth(1).color(Color.Yellow)
    .position({ bottom: this.bottom })
  Divider().strokeWidth(1).color(Color.Blue).vertical(true)
    .position({ left: this.left })
  Divider().strokeWidth(1).color(Color.Green).vertical(true)
    .position({ right: this.right })
}
.width(this.w)
.height(this.h)

详细方案

1.给Text设置背景图并将backgroundImageSize宽高都设置为100%,再使用backgroundImageResizable限定背景图拉伸区域。

2.使用Stack组件嵌套Image和Text,在Text组件onAreaChange事件中将宽高值给到Image。

核心代码

代码语言:ts
复制
List({ space: 10 }) {
  ForEach(this.leftData, (item: string) => {
    ListItem() {
      Text(item)
        .padding({
          top: 10,
          bottom: 10,
          left: 10,
          right: 20
        })
        .backgroundImage($r('app.media.bubble3'))
        .backgroundImageSize({
          width: '100%',
          height: '100%'
        })
        .backgroundImageResizable({
          slice: {
            top: 30,
            bottom: 16,
            left: 16,
            right: 24
          }
        })
    }
  }, (item: string) => item)
}
.width('50%')
.height('100%')
.alignListItem(ListItemAlign.End)
......
Stack() {
  Image($r('app.media.bubble3'))
    .width(this.item.textWidth)
    .height(this.item.textHeight)
    .resizable({
      slice: {
        top: 30,
        bottom: 16,
        left: 16,
        right: 24
      }
    })
  Text(this.item.content)
    .padding({
      top: 10,
      bottom: 10,
      left: 10,
      right: 20
    })
    .onAreaChange((_oldValue: Area, newValue: Area) => {
      this.item.textWidth = newValue.width as number
      this.item.textHeight = newValue.height as number
    })
}

写在最后

如果你觉得这篇内容对你还蛮有帮助,我想邀请你帮我三个小忙:

  • 点赞,转发,有你们的 『点赞和评论』,才是我创造的动力;
  • 关注小编,同时可以期待后续文章ing🚀,不定期分享原创知识;
  • 想要获取更多完整鸿蒙最新学习知识点,可关注B站:码牛课堂;

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 场景描述
  • 效果图
    • 详细方案
  • 写在最后
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档