Flutter中的弧渐变? [英] Arc gradients in Flutter?
问题描述
我有一个 Paint
对象,我试图用它来通过 canvas.drawArc
,但是这样做的唯一方法(至少根据我的研究)是使用 Shader
,但要获得 Shader $
Gradient
对象中的c $ c>,则必须使用 Gradient.createShader(Rect rect)
,长方形。我的问题是,有没有办法为弧形而不是矩形创建着色器?到目前为止,我可以参考以下内容:
I have a Paint
object and I'm trying to use it to paint an Arc Gradient using canvas.drawArc
, but the only way to do this (at least according to my research) is to use a Shader
, but to get a Shader
from a Gradient
object, you have to use Gradient.createShader(Rect rect)
, which takes a rectangle. My question is, is there any way to create a shader for an Arc and not a Rectangle? Here's what I have so far for reference:
Paint paint = new Paint()
..color = bgColor
..strokeCap = StrokeCap.round
..strokeWidth = 3.0
..style = PaintingStyle.stroke
..shader = new Gradient.radial(size.width / 2.0, size.height / 2.0, size.height / 3.0, Colors.transparent, timerColor, TileMode.mirror).createShader(/* I don't have a rect object */);
canvas.drawArc(..., paint);
推荐答案
所需的矩形实际上是一个正方形您要绘制的圆圈将适合。弧线只是那圆弧中掠过的弧度的一部分。使用 Rect.fromCircle
使用中心和半径创建此正方形。然后,您可以在创建渐变并绘制圆弧时使用该正方形。
The Rectangle that you need is actually a square into which the circle that you are drawing would fit. The arc is just a slice of pie from that circle swept through so many radians. Create this square using Rect.fromCircle
, using the centre and radius. You then use this square when creating the gradient and drawing the arc.
下面是一个示例
import 'dart:math';
import 'package:flutter/material.dart';
class X1Painter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
// create a bounding square, based on the centre and radius of the arc
Rect rect = new Rect.fromCircle(
center: new Offset(165.0, 55.0),
radius: 180.0,
);
// a fancy rainbow gradient
final Gradient gradient = new RadialGradient(
colors: <Color>[
Colors.green.withOpacity(1.0),
Colors.green.withOpacity(0.3),
Colors.yellow.withOpacity(0.2),
Colors.red.withOpacity(0.1),
Colors.red.withOpacity(0.0),
],
stops: [
0.0,
0.5,
0.7,
0.9,
1.0,
],
);
// create the Shader from the gradient and the bounding square
final Paint paint = new Paint()..shader = gradient.createShader(rect);
// and draw an arc
canvas.drawArc(rect, pi / 4, pi * 3 / 4, true, paint);
}
@override
bool shouldRepaint(X1Painter oldDelegate) {
return true;
}
}
class X1Demo extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(title: const Text('Arcs etc')),
body: new CustomPaint(
painter: new X1Painter(),
),
);
}
}
void main() {
runApp(
new MaterialApp(
theme: new ThemeData.dark(),
home: new X1Demo(),
),
);
}
这篇关于Flutter中的弧渐变?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!