在Flutter中将具有自定义尺寸和旋转度的图像绘制到CustomPaint中

时间:2019-09-24 15:59:58

标签: image flutter dart

如何在Flutter中将图像绘制到customPaint()上以指定其大小和旋转度? 通常,仅使用drawImage()绘制图像时,其尺寸即为像素尺寸。例如,以40 x 40的尺寸绘制40x40像素的图像。如何绘制相同的图像,但是尺寸为80x80,旋转角度为120°?我尝试过drawAtlas,但网上找不到任何东西。

这是我必须绘制的代码。 (它在屏幕的右上方绘制了一个20x20的矩形)。

class ParticlePainter extends CustomPainter {
  final List<GameObject> objects;

  @override
  void paint(Canvas canvas, Size size) {


    canvas.drawRect(

        Rect.fromCenter(
            height: 20,
            width: 20,
            center: Offset(0.0, 0.0)),

        Paint()
          ..color = Colors.red
          ..blendMode = BlendMode.darken);
    }

  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return true;
  }

  ParticlePainter(this.objects);
}

要获取图像,我正在使用此视频中的代码:Custom Paint in Flutter

Future<Image> _loadImage(File file) async{
   final data = await file.readAsBytesSync();
   return await decodeImageFromList(data);
}

1 个答案:

答案 0 :(得分:1)

看起来您可以在绘画功能中旋转画布本身。我的代码在下面。

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class ParticlePainter extends CustomPainter {
  // final List<GameObject> objects;

  @override
  void paint(Canvas canvas, Size size) {
    canvas.save();

    final degrees = 120;
    final radians = degrees * math.pi / 180;

    canvas.rotate(radians);

    canvas.drawRect(
        Rect.fromCenter(
          height: 20,
          width: 20,
          center: Offset(
            0.0,
            0.0,
          ),
        ),
        Paint()
          ..color = Colors.red
          ..blendMode = BlendMode.darken);

    canvas.restore();
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return true;
  }

  // ParticlePainter(this.objects);
}

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Yay"),
      ),
      body: CustomPaint(
        child: Container(),
        painter: ParticlePainter(),
      ),
    );
  }
}

对我来说,这会使框稍微偏离屏幕,但我希望它足以使您前进。如果您做的简单,则可以使用Transform.rotateRotatedBox并将CustomPaint包装在其中。