如何设置已定位文本块的背景颜色? [英] How do I format the background color for a positioned block of text?
问题描述
我有一个定位的Text元素,它位于Stack中Image元素的顶部。我想为该Text元素应用简单的背景色,以便它像标题框一样框住文本:
I have a positioned Text element that sits on top of an Image element in a Stack. I'd like to apply a simple background color to that Text element, so that it frames the text like a caption box:
我可以通过在该Stack中插入另一个容器作为子容器来做到这一点。但每次文本字符串更改时,我都必须重新计算宽度,这是次优的。有更好的方法吗?
I can do this by inserting a Container as another positioned child in that Stack. But I'd have to recalculate the width every time the text string changes, which is sub-optimal. Is there a better way?
var stack = new Stack(
children: <Widget>[
new Image.asset ( // background photo
"assets/texture.jpg",
fit: ImageFit.cover,
height: 600.0,
),
new Positioned ( // headline
child: new Container(
decoration: new BoxDecoration (
backgroundColor: Colors.black
),
),
left: 0.0,
bottom: 108.0,
width: 490.0,
height: 80.0,
),
new Positioned (
child: new Text (
"Lorem ipsum dolor.",
style: new TextStyle(
color: Colors.blue[500],
fontSize: 42.0,
fontWeight: FontWeight.w900
)
),
left: 16.0,
bottom: 128.0,
)
]
);
推荐答案
只需将Text元素嵌套为子元素在具有BoxDecoration(即背景色)的容器中;容器将拉伸以适合内部的文本。另外,可以为该Container指定填充,这样就无需对框的宽度/高度进行硬编码。
Just nest the Text element as a child within the Container that has the BoxDecoration (i.e. background color); the Container will stretch to fit the Text inside. Additionally, one can specify padding for that Container, which eliminates the need to hardcode a width/height for the box.
var stack = new Stack(
children: <Widget>[
new Image.asset ( // background photo
"assets/texture.jpg",
fit: ImageFit.cover,
height: 600.0,
),
new Positioned ( // headline
child: new Container(
child: new Text (
"Lorem ipsum dolor.",
style: new TextStyle(
color: Colors.blue[500],
fontSize: 42.0,
fontWeight: FontWeight.w900
)
),
decoration: new BoxDecoration (
backgroundColor: Colors.black
),
padding: new EdgeInsets.fromLTRB(16.0, 16.0, 16.0, 16.0),
),
left: 0.0,
bottom: 108.0,
),
]
);
这篇关于如何设置已定位文本块的背景颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!