Flutter - #34. AspectRatio

Pearl Lee·2021년 7월 23일
1

Flutter Widget

목록 보기
32/50

Flutter 일기
참고 : https://api.flutter.dev/flutter/widgets/AspectRatio-class.html









AspectRatio

오늘 배워볼 것은 AspectRatio.
자식 위젯을 특정한 비율로 만드는 클래스이다. aspectRatio에 원하는 비율 값을 적고, child 위젯을 설정하기만 하면 끝이다.

비율은 분수, 소수로 표현 가능하다. 분수로 적어도 되는 이유는 컴파일 타임에 dart 언어가 알아서 계산을 하기 때문이다. (공식 유튜브가 그렇대)
만약 aspectRatio를 3/2 로 표현하면, 너비가 3 / 높이가 2 이다.
소수로 표현하면? 1.5 일 경우 너비가 높이의 1.5배가 되는 것이다.

그런데 비율은 알겠는데 정확히 얼마만큼을 차지하게 될까?
일단 child 위젯 자신이 차지할 수 있는 최대한의 너비를 결정하고 나서, 높이는 aspectRatio에 설정한 값에 따라 결정된다고 한다. 그냥 위젯이 있는 공간 안에서 최대한으로 차지한다~ 정도인듯









코드 예시로 알아보자

오늘도 공식 페이지 예제를 가져와서 돌려보자

import 'package:flutter/material.dart';

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

/// This is the main application widget.
class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  static const String _title = 'Test AspectRatio';

  
  Widget build(BuildContext context) {
    return MaterialApp(
      title: _title,
      home: Scaffold(
        appBar: AppBar(title: const Text(_title)),
        body: const MyStatelessWidget(),
      ),
    );
  }
}

/// This is the stateless widget that the main application instantiates.
class MyStatelessWidget extends StatelessWidget {
  const MyStatelessWidget({Key? key}) : super(key: key);

  
  Widget build(BuildContext context) {
    return Center(
      child: Container(
        color: Colors.blue.withOpacity(0.7),
        alignment: Alignment.center,
        width: double.infinity,
        height: 100.0,
        child: AspectRatio(
          aspectRatio: 16 / 9,
          child: Container(
            color: Colors.green[300],
          ),
        ),
      ),
    );
  }
}




위의 코드에서 AspectRatio 의 부모 위젯은 Container이다.

child: Container(
        color: Colors.blue.withOpacity(0.7),
        alignment: Alignment.center,
        width: double.infinity,
        height: 100.0,

Alignment.center로 인해 이 Container의 자식 위젯은 Container의 한 가운데에 위치하게 된다.
width는 double.infinity로 주었으므로 화면 너비 전체이고, height만 100으로 설정되어 있다. 이 경우 AspectRatio로 감싼 Container위젯의 크기는 어떻게 될까?

우선 위에서 AspectRatio로 감싼 위젯은, 본인이 위치하는 공간 내부에서 차지할 수 있는 최대의 공간을 차지한다고 하였다. aspectRatio는 16 / 9 로 설정하였으므로, 높이가 더 짧다.
부모 위젯의 높이인 100만큼을 차지할 수 있고, 너비는 100 / 9 * 16 이 된다.




aspectRatio를 바꿔가며 실행한 화면을 보자.

aspectRatio : 16/9aspectRatio : 1aspectRatio : 5/2

너비와 높이의 비율에 따라, 초록색 위젯의 모양이 변하는 것을 볼 수 있다.
그리고 이게 끝이다. 정말이야...

const AspectRatio({
    Key? key,
    required this.aspectRatio,
    Widget? child,
  }) : assert(aspectRatio != null),
       assert(aspectRatio > 0.0),
       // can't test isFinite because that's not a constant expression
       super(key: key, child: child);

애초에 이 클래스는 그리 많은 속성을 갖지 않기 때문이지!









오늘의 일기는 여기까지!

profile
안 되면 되게 하라

0개의 댓글