我正在为主页设置背景图片。我正在从屏幕开始获取图像位置,并填充宽度而不是高度。
我在代码中遗漏了什么吗?颤振有图像标准吗?图片的大小是基于每部手机的屏幕分辨率吗?
class BaseLayout extends StatelessWidget{
@override
Widget build(BuildContext context){
return Scaffold(
body: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Image.asset("assets/images/bulb.jpg")
]
)
)
);
}
}
import 'package:flutter/material.dart';
void main() => runApp(DestiniApp());
class DestiniApp extends StatefulWidget {
@override
_DestiniAppState createState() => _DestiniAppState();
}
class _DestiniAppState extends State<DestiniApp> {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: SafeArea(
child: Scaffold(
appBar: AppBar(
backgroundColor: Color.fromRGBO(245, 0, 87, 1),
title: Text(
"Landing Page Bankground Image",
),
),
body: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: ExactAssetImage("images/appBack.jpg"),
fit: BoxFit.cover
),
),
),
),
),
);
}
}
输出:
我知道这个问题已经有很多答案了,但是这个解决方案在背景图像周围有一个颜色梯度,我想你会喜欢的
import 'package:flutter/material.dart';
class BackgroundImageExample extends StatelessWidget {
const BackgroundImageExample({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Stack(
children: [
backgroudImage(),
Scaffold(
backgroundColor: Colors.transparent,
body: SafeArea(
child: Column(
children: [
// your body content here
],
),
),
),
],
);
}
Widget backgroudImage() {
return ShaderMask(
shaderCallback: (bounds) => LinearGradient(
colors: [Colors.black, Colors.black12],
begin: Alignment.bottomCenter,
end: Alignment.center,
).createShader(bounds),
blendMode: BlendMode.darken,
child: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('your image here'), /// change this to your image directory
fit: BoxFit.cover,
colorFilter: ColorFilter.mode(Colors.black45, BlendMode.darken),
),
),
),
);
}
}
我不确定我是否理解你的问题,但如果你想让图像填充整个屏幕,你可以使用一个适合BoxFit.cover的DecorationImage。
class BaseLayout extends StatelessWidget{
@override
Widget build(BuildContext context){
return Scaffold(
body: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage("assets/images/bulb.jpg"),
fit: BoxFit.cover,
),
),
child: null /* add child content here */,
),
);
}
}
对于你的第二个问题,这里有一个关于如何将依赖分辨率的资产图像嵌入到应用程序中的文档链接。
其他答案都很棒。这是另一种方法。
这里我使用sizebox .expand()来填充可用空间,并将严格的约束传递给它的子代(Container)。
BoxFit。cover enum缩放图像并覆盖整个屏幕
Widget build(BuildContext context) {
return Scaffold(
body: SizedBox.expand( // -> 01
child: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: NetworkImage('https://flutter.github.io/assets-for-api-docs/assets/widgets/owl-2.jpg'),
fit: BoxFit.cover, // -> 02
),
),
),
),
);
}
我们可以使用Container并将其高度标记为无穷大
body: Container(
height: double.infinity,
width: double.infinity,
child: FittedBox(
fit: BoxFit.cover,
child: Image.network(
'https://cdn.pixabay.com/photo/2016/10/02/22/17/red-t-shirt-1710578_1280.jpg',
),
),
));
输出: