【Flutter】容器類組件之剪裁


前言

Flutter中提供了一些剪裁函數,用於對組件進行剪裁。

剪裁Widget 作用
ClipOval 子組件為正方形時剪裁為內貼圓形,為矩形時,剪裁為內貼橢圓
ClipRRect 將子組件剪裁為圓角矩形
ClipRect 剪裁子組件到實際占用的矩形大小(溢出部分剪裁)

接口描述


const ClipOval({ Key key, this.clipper, this.clipBehavior = Clip.antiAlias, Widget child }) : super(key: key, child: child);

const ClipRRect({
    Key key,
    this.borderRadius,
    this.clipper,
    this.clipBehavior = Clip.antiAlias,
    Widget child,
  }) : assert(borderRadius != null || clipper != null),
       assert(clipBehavior != null),
       super(key: key, child: child);

const ClipRect({ Key key, this.clipper, this.clipBehavior = Clip.hardEdge, Widget child }) : super(key: key, child: child);

代碼示例

// 剪裁 clip

// 剪裁Widget	   作用
// ClipOval	     子組件為正方形時剪裁為內貼圓形,為矩形時,剪裁為內貼橢圓
// ClipRRect	   將子組件剪裁為圓角矩形
// ClipRect	     剪裁子組件到實際占用的矩形大小(溢出部分剪裁)

import 'package:flutter/material.dart';

class ClipTest extends StatelessWidget {

  @override
  Widget build(BuildContext context)  {
    // 頭像
    Widget avatar = Image.asset('assets/images/avatar.png', width: 60,);
    return Scaffold(
      appBar: AppBar(
        title: Text('剪裁'),
      ),
      body: Column(
        children: <Widget>[
          // 不裁剪
          avatar,
          // 裁剪為圓形
          ClipOval(child: avatar,),
          // 裁剪為圓角矩形
          ClipRRect(
            borderRadius: BorderRadius.circular(5.0),
            child: avatar,
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Align(
                alignment: Alignment.topLeft,
                // 寬度設為原來的一半,另一半會溢出
                widthFactor: .5,
              ),
              Text('Hello world!', style: TextStyle(color: Colors.green),)
            ],
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              // 將溢出部分剪裁
              ClipRect(
                child: Align(
                  alignment: Alignment.topLeft,
                  widthFactor: .5,
                  child: avatar,
                ),
              ),
              Text('Hello world!', style: TextStyle(color: Colors.green),)
            ],
          ),
          DecoratedBox(
            decoration: BoxDecoration(
              color: Colors.red,
            ),
            child: ClipRect(
              // 使用自定義的clipper
              clipper: MyClipTest(),
              child: avatar,
            ),
          )
        ],
      ),
    );
  }
}


// 自定義剪裁
class MyClipTest extends CustomClipper<Rect> {
  @override
  Rect getClip(Size size) => Rect.fromLTWH(10.0, 15.0, 40.0, 30.0);

  @override
  bool shouldReclip(CustomClipper<Rect> oldClipper) => false;
}

總結

剪裁是在layout完成后的繪制階段進行的,所以不會影響組件的大小,這和Transform原理是相似的。


免責聲明!

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



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