HarmonyOS 鸿蒙Next开发支持.9图片么?像安卓一样,做自动适配
HarmonyOS 鸿蒙Next开发支持.9图片么?像安卓一样,做自动适配
【解决方案】
-
通过调整Image中的width和height来将文字放到想要的图片中的位置,通过resizable属性,设置ResizableOptions参数,设置拉伸时上下左右距离一致,实现.9图。
代码如下:
import { MeasureText } from '@kit.ArkUI'
@Component
export struct CommonStyle {
@Prop text: string = '';
@State left: number = 10;
@State right: number = 10;
@State top: number = 10;
@State bottom: number = 10;
@State line: number = 2;
@State textSize: SizeOptions = MeasureText.measureTextSize({ textContent: this.text });
build() {
Stack() {
Image($r("app.media.11"))
.width(px2vp(Number(`${this.textSize.width}`)) < 350 ? 60 + px2vp(Number(`${this.textSize.width}`)) : 380)
.height(this.text.length < 40 ? 50 + px2vp(Number(`${this.textSize.height}`)) :
50 + (px2vp(Number(`${this.textSize.height}`)) * this.line))
.resizable({
slice: {
top: this.top,
left: this.left,
bottom: this.bottom,
right: this.right
}
})
Text(this.text)
.fontColor(Color.White)
}
.width(350)
.height(200)
}
}
@Entry
@Component
struct ChatBubbleStretchDemo {
build() {
Column() {
CommonStyle({ text: '一行文字' })
CommonStyle({ text: '两行文字两行文字两行文字两行文字两行文字两行文字' })
CommonStyle({
text: '多行文字多行文字多行文字多行文字多行文字多行文字多行文字多行文字多行文字多行文字多行文字多行文字'
})
}
.backgroundColor(Color.White)
.height('100%')
.width('100%')
}
}
- 亦可参考官方FAQ实现.9图功能。
【背景知识】
Image是图片组件,常用于在应用中显示图片。Image组件提供与点九图相同功能的API设置,通过设置resizable属性来配置ResizableOptions,即图像拉伸时的大小调整选项。ResizableOptions的参数slice包含top、left、bottom和right四个属性,分别表示图片在上下左右四个方向拉伸时保持不变的距离。
更多关于HarmonyOS 鸿蒙Next开发支持.9图片么?像安卓一样,做自动适配的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
是的,HarmonyOS 的 ArkUI 框架提供了类似 Android .9 图的适配能力,可以通过组件属性实现图片拉伸时的智能适配。
实现方案
使用 resizable 属性:Image 组件的 resizable 属性支持设置拉伸规则,通过 slice 参数定义图像四个方向不可变形的区域,效果与 .9 图九宫格拉伸一致:
Image($r('app.media.background_image'))
.width(200)
.height(200)
.resizable({
slice: {
top: 40, // 顶部保留区域高度(vp)
right: 40, // 右侧保留区域宽度
bottom: 40,
left: 40
}
})
说明:slice 的 top/right/bottom/left 定义图像拉伸时保留的固定区域(类似 .9 图的边线标记)。
单位处理:若设计图单位为像素(px),需转换为虚拟像素(vp)或在代码中直接使用 px 单位。
鸿蒙Next支持.9图片格式,用于界面元素的自动适配。其实现机制与安卓类似,通过定义图片的可拉伸区域和内容区域来实现不同屏幕尺寸的自适应显示。开发者可在鸿蒙项目中直接使用.9.png格式的图片资源,系统会自动处理缩放和显示适配。
是的,HarmonyOS Next支持.9.png格式的九宫格图片,其适配机制与Android类似。开发时可直接在资源目录(如resources/base/media
)中放置.9图片,系统会根据拉伸区域和内容区域的标记自动处理缩放与适配,无需额外代码适配。注意需使用合规的.9图片制作工具生成文件,确保黑边标记准确。