Flutter基礎:第四節 Image 組件的使用

                                        第四節 Image 組件的使用

 

注:圖片素材來自網絡,如有侵權,敬請告知,立即刪除

在項目中,圖片的使用是必不可少的。這一節我們學習一下Image的使用。

一、加載圖片的四種方法

  • Image.asset:加載資源圖片,加載項目資源文件中的圖片。
  • Image.network:加載網絡資源圖片,需要加入圖片網址(http://xx.xx)。
  • Image.file:加載本地文件中的圖片,需要填寫絕對路徑。
  • Image.memory: 加載Uint8List資源圖片。

接下來,我們以加載網絡爲例,來進行演示。我們從網上找到一張圖片,網址爲http://file02.16sucai.com/d/file/2015/0408/779334da99e40adb587d0ba715eca102.jpg

然後,我們通過Image來加載這張圖片。

代碼如下:

import 'package:flutter/material.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return new MaterialApp(
      title: "Hello World",
      home: new Scaffold(
        appBar: new AppBar(
          title: new Text("Hello world"),
        ),
        body: new Container(
          child: new Image.network(
              "http://file02.16sucai.com/d/file/2015/0408/779334da99e40adb587d0ba715eca102.jpg"),
        ),
      ),
    );
  }
}

 效果圖:

 

 

二、fit屬性

fit:控制圖片的拉伸和擠壓。

  • BoxFit.fill:全圖顯示,圖片會被拉伸,並充滿父容器(圖片可能會變形)。

  • BoxFit.contain:全圖顯示,顯示原比例,可能有空隙。

  • BoxFit.cover:圖片充滿整個容器,並且不變形。可能拉伸、裁剪。

  • BoxFit.fitWidth:橫向充滿,可能拉伸或裁剪。

  • BoxFit.fitHeight :豎向充滿,可能拉伸或裁剪。

  • BoxFit.scaleDown:效果和contain類似。注:此屬性不允許顯示超過源圖片大小,只能小,不能大。

以BoxFit.cover爲例,代碼如下:

import 'package:flutter/material.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return new MaterialApp(
      title: "Hello World",
      home: new Scaffold(
        appBar: new AppBar(
          title: new Text("Hello world"),
        ),
        body: new Container(
          width: 400.0,
          height: 200.0,
          child: new Image.network(
            "http://a0.att.hudong.com/16/12/01300535031999137270128786964.jpg",
            fit: BoxFit.cover,
          ),
        ),
      ),
    );
  }
}

 效果圖:

 

三、圖片混合模式

 此功能主要是可以讓圖片改變顏色,需要 colorBlendMode 屬性和 color 屬性聯合使用,會產生意想不到的效果。

我們在上面的例子中,繼續加入藍色,colorBlendMode 選擇 BlendMode.colorDodge。

代碼如下:

  child: new Image.network(
            "http://a0.att.hudong.com/16/12/01300535031999137270128786964.jpg",
            color: Colors.blueAccent,
            colorBlendMode: BlendMode.colorDodge,
          ),

 效果圖:

我們通過屬性,改變了圖片的顏色,是不是很神奇。當然我們還可以改變爲其他的形式(例如: BlendMode.colorBurn 、  BlendMode.darken  、 BlendMode.difference  等),需要開發者去自己嘗試,然後選擇適合自己應用風格的屬性。

 

四、repeat屬性

repeat:圖片重複展示。

可以讓圖片在特定容器內進行重複的展示。

  • ImageRepeat.repeat : 橫向和縱向同時進行重複,直到鋪滿整個容器。

  • ImageRepeat.repeatX: 只進行橫向重複,縱向不重複。

  • ImageRepeat.repeatY:只進行縱向重複,橫向不重複。

編寫代碼,讓圖片進行橫向重複。代碼如下:

  child: new Image.network(
            "http://a0.att.hudong.com/16/12/01300535031999137270128786964.jpg",
            repeat: ImageRepeat.repeatX,
          ),

效果圖:

 

好了,本節課程到這裏就結束了。我也是flutter學習者,喜歡請關注我吧,我們下節見 ~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章