简体   繁体   中英

How to create a hexagon clippath on flutter?

I'm trying to use a hexagon profile picture, but I'm having trouble using clip path with flutter.

The CSS code for the hexagon is this:

-webkit-clip-path: polygon(50% 0%, 100% 25%, 100% 75%, 50% 100%, 0% 75%, 0% 25%);
    clip-path: polygon(50% 0%, 100% 25%, 100% 75%, 50% 100%, 0% 75%, 0% 25%);

how can I do it on flutter?

code

import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Hexagon', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(title: 'Hexagon'), ); } } class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { @override Widget build(BuildContext context) { return Scaffold( body: Padding( padding: const EdgeInsets.all(50.0), child: ClipPath( child: Container( color: Colors.amber, ), clipper: _MyClipper(), ), ), ); } } class _MyClipper extends CustomClipper<Path> { @override Path getClip(Size size) { final path = Path(); path.lineTo(0, 0); path.lineTo(size.width, 0); path.lineTo(size.width, size.height * 0.8); path.lineTo(size.width * 0.8, size.height); path.lineTo(size.width * 0.2, size.height); path.lineTo(0, size.height * 0.8); path.lineTo(0, 0); path.close(); return path; } @override bool shouldReclip(CustomClipper<Path> oldClipper) => false; }

or you can use a package called

flutter_custom_clippers: ^2.0.0

Let's use ClipPath to get this shape and follow the css the way you did. 50% 0% mean (x, y) and also same for lineTo(x,y) and moveTo .


class HexagonClipper extends CustomClipper<Path> {
  @override
  Path getClip(Size size) {
    Path path = Path();

    path
      ..moveTo(size.width / 2, 0) // moving to topCenter 1st, then draw the path
      ..lineTo(size.width, size.height * .25)
      ..lineTo(size.width, size.height * .75)
      ..lineTo(size.width * .5, size.height)
      ..lineTo(0, size.height * .75)
      ..lineTo(0, size.height * .25)
      ..close();

    return path;
  }

  @override
  bool shouldReclip(covariant CustomClipper<Path> oldClipper) {
    return false;
  }
}

And use like

  ClipPath(
            clipper: HexagonClipper(),
            child: Container(
              width: 100, /// controll the size and color
              height: 110,
              color: Colors.amber,
            ),
          )

Result

在此处输入图片说明

learn more about ClipPath

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM