通过onAreaChange监听Text的变化,并设置图片组件的resizable属性,设置顶部、右侧、底部、左侧的距离,使其边缘部分在图片拉伸时不会发生变化,仅图片中央区域被拉伸,从而动态调整Image的大小位置等。
@Entry
@Component
struct TextView {
@State textWidth: Length = 0;
@State fontSize: number = 16;
build() {
Column({ space: 16 }) {
Button('increase font size')
.margin({ top: 16 })
.onClick(() => {
this.fontSize += 2;
});
Text('这是一个Text')
.fontSize(`${this.fontSize}fp`)
.onAreaChange((oldValue: Area, newValue: Area) => {
this.textWidth = newValue.width;
})
.padding({
left: '5vp',
right: '5vp'
});
Image($r('app.media.img1')) // 图片资源文件需自行替换
.width(this.textWidth)
.resizable({
slice: {
top: '5vp',
right: '5vp',
left: '5vp',
bottom: '5vp'
}
});
}
.height('100%')
.width('100%');
}
} 实现效果如下:增大Text文本,图片对应变大。
