flutter 图片圆形裁剪

11 min read
import 'package:flutter/material.dart';

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

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

  Widget _getRoundImage(String imageName, double size) {
    return Container(
      width: size,
      height: size,
      clipBehavior: Clip.antiAlias,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.all(Radius.circular(size / 2)),
      ),
      child: Image.network(
        imageName,
        width: size,
        height: size,
        fit: BoxFit.cover,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
          appBar: AppBar(
            title: const Text('Flutter Demo'),
          ),
          body: _getRoundImage('https://picsum.photos/200/300', 200)),
    );
  }
}

Clip.antiAlias: 抗锯的方式进行裁剪,这种方式的裁剪效果最好,但是更耗资源

Clip.hardEdge:从名字就知道,这种方式很粗糙,但是裁剪的效率最快;

Clip.antiAliasSaveLayer:最为精细的裁剪,但是非常慢,不建议使用;

Clip.none:默认值,如果内容区没有超出容器边界的话,不会做任何裁剪。内容超出边界的话需要使用别的裁剪方式防止内容溢出。