【关键字】
背景图拉伸 / Image组件 / resizable
【问题描述】
给一个row设置了背景图,但是需要背景图四周不拉伸,只拉伸中间区域,目前没有找到合适的API,请问有相关的API吗?
希望达到的效果:
因为Text组件的文本内容长度不定,可以有一行,也可以有三行,希望背景图可以做到四周不拉伸,中间区域拉伸,用于达到图片包裹文字的效果,也就是下面的效果(下图为单行文本,多行也为包裹效果)
实际实现的效果:设置了backgroundImageSize(ImageSize.Cover)
代码如下:
@Component
export struct PrivacyTipsView {
@Prop tipsStr:string
build() {
Row(){
Text(this.tipsStr)
.fontSize(12)
.fontColor(0xdc6e1d)
.margin({top:15})
.padding({left:10,right:10})
}
.backgroundImage($r('app.media.privacy_tip'))
.backgroundImageSize(ImageSize.Cover)
.width('86%')
.margin({left:32,right:24})
}
}
【解决方案】
API 11的row.backgroundImage设置背景图不支持四周不拉伸,只拉伸中间区域的效果,Image组件新增了resizable属性设置图像拉伸时可调整大小的图像选项。
开发指南:
示例代码如下:
@Entry
@Component
struct Index {
@State tipsStr: string = 'hello world11111111111111'
build() {
Flex({ direction: FlexDirection.Column }) {
Text(this.tipsStr)
.fontSize(20)
.fontColor(0xdc6e1d)
.margin({ top: 10 })
.padding({ top: 10, left: 10, right: 10 })
.background(this.createBackgroundImg())
TextInput({ text: $$this.tipsStr }).margin({ top: 20 })
}
}
@Builder createBackgroundImg() {
Image($r('app.media.text'))
.objectFit(ImageFit.Fill)
.width("100%")
.height("100%")
.resizable({ slice: { top: 10, left: 10, bottom: 10, right: 10 } })
}
}