簡體   English   中英

如何獲得在腳手架下縮放時不會改變的 CustomPaint?

[英]How do I get a CustomPaint that doesn't change when scaled under a Scaffold?

如果我在具有縮小比例的畫布上繪制相同的圖形——通過將v = 100000.0替換為v = 1000.0在下面的代碼中(這里解釋了這個想法),

import 'package:flutter/material.dart';

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

const v = 10000.0;

class Painter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final mypaint = Paint()
    ..style = PaintingStyle.stroke
    ..strokeWidth = 0.012 * v
    ..color = Colors.blue;

    canvas.drawCircle(
      Offset(1.5 * v, 1 * v),
      1 * v, mypaint);
  }

  @override
  bool shouldRepaint(Painter oldDelegate) => false;
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "My App",
      home: FittedBox(
        child: SizedBox(
          width: 3 * v,
          height: 2 * v,
          child: CustomPaint(
            painter: Painter()
            ),
        ),
      ),
    );
  }
}

我仍然得到相同的圖像。

比例不變渲染

但是如果我把MaterialApp放在Scaffold里面,

import 'package:flutter/material.dart';

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

const v = 10000.0;

class Painter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final mypaint = Paint()
    ..style = PaintingStyle.stroke
    ..strokeWidth = 0.012 * v
    ..color = Colors.blue;

    canvas.drawCircle(
      Offset(1.5 * v, 1 * v),
      1 * v, mypaint);
  }

  @override
  bool shouldRepaint(Painter oldDelegate) => false;
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "My App",
      home: Scaffold(
        appBar: AppBar(
          title: const Text('My Title'),
        ),
        body: FittedBox(
          child: SizedBox(
            width: 3 * v,
            height: 2 * v,
            child: CustomPaint(
              painter: Painter()
              ),
          ),
        ),
      ),
    );
  }
}

對於v = 10000.0 ,我仍然得到左側的圖像,但是使用v = 100.0時,我得到的是右側的圖像。

更改比例時圖像會更改

如何使用Scaffold獲得比例不變的CustomPaint

順便說一句, Scaffold的主體也不再居中。 你明白為什么嗎?

定制油漆與尺寸無關。 它采用調用者發送的大小。 如果您將 sizedbox 的大小設置為 200x200,它將在該空間中繪制。 現在 10k 或 1k 將給出相同的結果,因為設備上沒有空間來繪制某些東西,因為設備的寬度小於 1k。 但是 10、100 和 1k 會顯示不同大小的圓圈。 在這里定義比例的唯一因素是 SizedBox 的大小

畫圓也可以寫成

canvas.drawCircle(Offset(size.height / 2, size.width / 2), size.width/2);

現在,如果您通過一個 100x100 大小的盒子,它將繪制一個直徑為 100 的圓

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM