如何在画布上约束图像

问题描述 投票:0回答:1

我想在画布上绘制200x200像素的图像,然后对其进行其他处理。我的图片为900x690,因此理想情况下,我想“裁剪”图片以使用Android术语。由于某些原因,This video告诉我们先使用FittedBox,然后再使用SizedBox。我也尝试将两者都放入Container。我尝试将容器大小,盒子大小和客户绘画工具Size设置为200x200,所有内容均会产生全屏图像。谁知道我在做什么错:)

这里是代码:

import 'dart:typed_data';
import 'dart:ui' as ui;

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart' show rootBundle;

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  ui.Image image;

  @override
  void initState() {
    super.initState();
    load('images/noodlejpg.jpg').then((i) {
      setState(() {
        image = i;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(backgroundColor: Colors.blue, title: Text('I am a title')),
      backgroundColor: Colors.teal,
      body: SafeArea(
        child: FittedBox(
          child: SizedBox(
            width: 200.0,
            height: 200.0,
            child: CustomPaint(
              painter: MyPainter(image),
            ),
          ),
        ),
      ),
    );
  }

  Future<ui.Image> load(String asset) async {
    ByteData data = await rootBundle.load(asset);
    ui.Codec codec = await ui.instantiateImageCodec(data.buffer.asUint8List());
    ui.FrameInfo fi = await codec.getNextFrame();
    return fi.image;
  }
}

class MyPainter extends CustomPainter {
  ui.Image image;

  MyPainter(this.image);

  @override
  void paint(Canvas canvas, Size size) {
    var paint = new Paint();
    paint.blendMode = BlendMode.srcIn;
    paint.isAntiAlias = true;

    if (image != null) canvas.drawImage(image, Offset.zero, paint);
  }

  @override
  bool shouldRepaint(MyPainter oldDelegate) {
    return image != oldDelegate.image;
  }
}
flutter dart flutter-canvas
1个回答
0
投票

设置图像编解码器大小:instantiateImageCodec function

Future<Codec> instantiateImageCodec (
       Uint8List list,
       {int targetWidth,
       int targetHeight}
)
© www.soinside.com 2019 - 2024. All rights reserved.