如何在Flutter中裁剪图像?

Set*_*add 12 dart flutter

假设我有一个长方形的肖像图像:

在此输入图像描述

我想裁剪它,使它像这样渲染:

在此输入图像描述

我怎么能在Flutter做到这一点?

(我不需要调整图像大小.)

(图片来自https://flic.kr/p/nwXTDb)

Col*_*son 28

我可能会用BoxDecoration一个DecorationImage.您可以使用alignmentfit属性来确定图像的裁剪方式.AspectRatio如果您不想硬编码高度,可以使用小部件Container.

截图

import 'package:flutter/material.dart';

void main() {
  runApp(new MaterialApp(
    home: new MyHomePage(),
  ));
}

class MyHomePage extends StatelessWidget {

  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text("Image Crop Example"),
      ),
      body: new Center(
        child: new AspectRatio(
          aspectRatio: 487 / 451,
          child: new Container(
            decoration: new BoxDecoration(
              image: new DecorationImage(
                fit: BoxFit.fitWidth,
                alignment: FractionalOffset.topCenter,
                image: new NetworkImage('https://i.stack.imgur.com/lkd0a.png'),
              )
            ),
          ),
        ),
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 您正在尝试在渲染文件时对其进行裁剪。但是,我想存储图像的裁剪版本,然后进行渲染。你知道任何这样的技术或包吗? (4认同)

Cop*_*oad 19

fit为您的小部件提供一个因素Image,然后将其包装在AspectRatio.

AspectRatio(
  aspectRatio: 1.5, 
  child: Image.asset(
    'your_image_asset',
    fit: BoxFit.cover,
  ),
)
Run Code Online (Sandbox Code Playgroud)

  • 到目前为止最有帮助的答案<3 Bravo! (3认同)

Wae*_*lay 8

Take a look to brendan-duncan/image, it's platform-independent library to manipulate images in Dart.

您可以使用该功能:

Image copyCrop(Image src, int x, int y, int w, int h);
Run Code Online (Sandbox Code Playgroud)

  • 我不认为 Flutter 提供了一种从 ui.Image 中获取解码图像的简单方法。但是如果你使用 brendan 的图像库进行解码,你可以调用 `image.getBytes()` 并将其传递给一个 `new Image.memory` (2认同)
  • 是否可以添加有关如何从网络图像在 Flutter 中执行此操作的示例?我正在尝试以特定的 `{ x: 897, y: 235, width: 845, height: 845 }` 值裁剪图像,但找不到任何适合我的东西。 (2认同)

Mar*_*ary 8

您还可以直接将Image类与BoxFit一起使用,并执行以下操作:

new Image.asset(
  stringToImageLocation,
  fit: BoxFit.cover,
)
Run Code Online (Sandbox Code Playgroud)

  • 你好,我想在两个方向上显示图像的一部分。假设我有 1080x1920 图像,我想显示 (x=100~200,y=300~400) 部分。因此我不能使用这种拟合+对齐方法。我怎样才能这样做呢?谢谢! (3认同)

Dev*_*ven 6

仅使用这两个属性为我工作:

CachedNetworkImage(
  fit: BoxFit.cover,// OR BoxFit.fitWidth
  alignment: FractionalOffset.topCenter,
  ....
)
Run Code Online (Sandbox Code Playgroud)