HarmonyOS鸿蒙Next中如何像安卓一样的.9图,实现图片指定区域拉伸
HarmonyOS鸿蒙Next中如何像安卓一样的.9图,实现图片指定区域拉伸 如何像安卓一样的.9图,实现图片指定区域拉伸
当前Image对于.9图的使用是给Image组件设置resizable属性,达到图片局部拉伸的效果,文档可参考:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/ts-basic-components-image#resizable11。
以下是简单的使用例子:
[@Entry](/user/Entry)
[@Component](/user/Component)
export struct Image9SliceSample {
[@State](/user/State) left: number = 30;
[@State](/user/State) right: number = 2;
[@State](/user/State) top: number = 2;
[@State](/user/State) bottom: number = 2;
[@State](/user/State) fit: ImageFit = ImageFit.Cover;
[@State](/user/State) w: number = 100
[@State](/user/State) h: number = 200
[@Builder](/user/Builder)
ImageBuilder() {
Image($r('app.media.image1'))
.resizable({
slice: {
top: `${this.top}px`,
left: `${this.left}px`,
bottom: `${this.bottom}px`,
right: `${this.right}px`,
}
})
.width(`${this.w}px`)
.height(`${this.h}px`)
}
build() {
Column({ space: 20 }) {
Text("123")
.background(this.ImageBuilder)
.width(`${this.w}px`)
.height(`${this.h}px`);
Blank().height(80)
.height(`${this.h}px`)
Row() {
Button("add top to " + this.top).fontSize(10)
.onClick(() => {
this.top += 1
})
Button("add bottom " + this.bottom).fontSize(10)
.onClick(() => {
this.bottom += 1
})
Button("add left " + this.left).fontSize(10)
.onClick(() => {
this.left += 1
})
Button("add right " + this.right).fontSize(10)
.onClick(() => {
this.right += 1
})
}
Row() {
Button("reduce top to " + this.top).fontSize(10)
.onClick(() => {
this.top -= 1
})
Button("reduce bottom " + this.bottom).fontSize(10)
.onClick(() => {
this.bottom -= 1
})
Button("reduce left " + this.left).fontSize(10)
.onClick(() => {
this.left -= 1
})
Button("reduce right " + this.right).fontSize(10)
.onClick(() => {
this.right -= 1
})
}
Row() {
Button("add w").fontSize(10)
.onClick(() => {
this.w += 10
})
Button("add h").fontSize(10)
.onClick(() => {
this.h += 10
})
}
}
.backgroundColor(Color.Orange)
.width('100%').height('100%')
}
}更多关于HarmonyOS鸿蒙Next中如何像安卓一样的.9图,实现图片指定区域拉伸的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
屁用没有,
在HarmonyOS鸿蒙Next中,实现类似安卓的.9图功能,可以通过使用Slice组件来实现图片的指定区域拉伸。Slice组件允许你定义图片的四个边距(上、下、左、右),并指定这些边距内的区域作为内容区域。具体步骤如下:
-
准备图片资源:首先,确保你的图片资源符合.9图的要求,即图片的四个边需要有明确的黑线标记来定义可拉伸区域和内容区域。
-
使用
Slice组件:在布局文件中,使用Slice组件来引用你的图片资源,并设置slice属性来定义拉伸区域。slice属性接受一个Insets对象,该对象定义了图片的上、下、左右边距。 -
定义拉伸区域:在
slice属性中,通过设置top、bottom、left、right的值来指定图片的拉伸区域。这些值表示从图片边缘到可拉伸区域的像素距离。 -
应用布局:将
Slice组件应用到你的布局中,确保图片在不同屏幕尺寸下能够正确拉伸。
示例代码:
<Slice
ohos:width="match_parent"
ohos:height="match_parent"
ohos:slice="10,10,10,10"
ohos:image_src="$media:nine_patch_image"/>
在上述代码中,slice属性设置为10,10,10,10,表示图片的四个边距各为10像素,这些边距内的区域将被拉伸。image_src属性指定了图片资源。
通过这种方式,你可以在HarmonyOS鸿蒙Next中实现类似安卓的.9图功能,确保图片在不同设备上的适配性和显示效果。


