【Flutter】容器類組件之變換


前言

Transform可以在其子組件繪制時對其應用一些矩陣變換來實現一些特效。

接口描述

const Transform({
    Key key,
    @required this.transform,
    this.origin,
    this.alignment,
    this.transformHitTests = true,
    Widget child,
  }) : assert(transform != null),
       super(key: key, child: child);

代碼示例

// 變換(Transform)
// Transform可以在其子組件繪制時對其應用一些矩陣變換來實現一些特效。

import 'dart:math' as math;
import 'package:flutter/material.dart';

class TransformTest extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('變換'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[

            // 4D矩陣
            Container(
              color: Colors.black,
              child: Transform(
                // 相對於坐標系原點的對齊方式
                alignment: Alignment.topRight,
                // Matrix4是一個4D矩陣。沿Y軸傾斜0.3弧度
                transform: Matrix4.skewY(0.3),
                child: Container(
                  padding: EdgeInsets.all(8.0),
                  color: Colors.deepOrange,
                  child: Text('Transform'),
                ),
              ),
            ),

            // 平移
            DecoratedBox(
              decoration: BoxDecoration(color: Colors.red),
              // 接收一個offset參數,可以在繪制時沿x、y軸對子組件平移指定的距離
              child: Transform.translate(offset: Offset(-20.0, -5.0), child: Text('Transform.'),),
            ),

            // 旋轉
            DecoratedBox(
              decoration: BoxDecoration(color: Colors.red),
              child: Transform.rotate(angle: math.pi/2, child: Text('Transform.'),),
            ),

            // 縮放
            DecoratedBox(
              decoration: BoxDecoration(color: Colors.red),
               child: Transform.scale(scale: 5, child: Text('Transform.'),),
            ),

            // 驗證變換原理
            Text("你好", style: TextStyle(color: Colors.green, fontSize: 18.0),),

            // RotatedBox
            // RotatedBox和Transform.rotate功能相似,它們都可以對子組件進行旋轉變換,
            // 但是有一點不同:RotatedBox的變換是在layout階段,會影響在子組件的位置和大小。
            DecoratedBox(
              decoration: BoxDecoration(color: Colors.red),
              // 將Transform.rotate換成RotatedBox
              child: RotatedBox(
                // 旋轉90度,四分之一圈
                quarterTurns: 1,
                child: Text('Transform.'),
              ),
            ),
            Text("你好", style: TextStyle(color: Colors.green, fontSize: 18.0),),

          ],
        ),

      ),
    );
  }
}

總結

Transform的變換是應用在繪制階段,而並不是應用在布局階段,所以無論對子組件應用何種變化,其占用空間的大小和在屏幕的位置是固定不變的,因為這些是在布局階段就確定的。
由於矩陣變化只會作用在繪制階段,所以在某些場景下,在UI需要變化時,可以通過矩陣變化來達到視覺上UI改變,而不需要重新觸發build流程,這樣會節省layout的開銷,所以性能會比較好。
由於RotatedBox是作用於layout階段,所以子組件會旋轉90度(而不只是繪制的內容),decoration會作用到子組件所占用的實際空間上。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM