乐闻世界logo
搜索文章和话题

How to draw a custom rounded rectangle border ( ShapeBorder ), in Flutter?

1个答案

1

In Flutter, if you want to draw a custom rounded rectangle border, you can create a new border class by extending the ShapeBorder class. This allows you to fully control the shape, style, and behavior of the border according to your specific requirements. I will demonstrate how to achieve this through step-by-step examples.

Step 1: Create a New ShapeBorder Class

First, we need to create a new class that inherits from ShapeBorder. In this class, we primarily implement two methods: paint() and getOuterPath().

dart
import 'package:flutter/material.dart'; class CustomRoundedRectangleBorder extends ShapeBorder { final double width; final double borderRadius; CustomRoundedRectangleBorder({this.width = 1.0, this.borderRadius = 12.0}); EdgeInsetsGeometry get dimensions => EdgeInsets.all(width); Path getOuterPath(Rect rect, {TextDirection? textDirection}) { return Path() ..addRRect(RRect.fromRectAndRadius( rect, Radius.circular(borderRadius), )); } void paint(Canvas canvas, Rect rect, {TextDirection? textDirection}) { final paint = Paint() ..style = PaintingStyle.stroke ..strokeWidth = width ..color = Colors.blue; canvas.drawRRect( RRect.fromRectAndRadius( rect.deflate(width / 2), Radius.circular(borderRadius - width / 2), ), paint, ); } ShapeBorder scale(double t) { return CustomRoundedRectangleBorder( width: width * t, borderRadius: borderRadius * t, ); } }

Step 2: Use the Custom ShapeBorder

Once you have defined your own ShapeBorder subclass, you can use it in Flutter widgets. For example, when using the Container widget, you can set its decoration property to specify the Shape as your custom CustomRoundedRectangleBorder.

dart
Container( width: 200, height: 100, decoration: ShapeDecoration( shape: CustomRoundedRectangleBorder( width: 3.0, borderRadius: 20.0, ), color: Colors.white, ), child: Center(child: Text("Custom Border")), )

Summary

By following these steps, you can create a rectangular border with customized rounded corners. Adjust the values of borderRadius and width to control the corner radius and line width of the border. This approach offers high flexibility and customizability, making it easy to adapt to various design requirements.

2024年7月18日 20:05 回复

你的答案