在 Flutter Canvas 中使用 Gradient 和 Paint 对象 [英] Use Gradient with Paint object in Flutter Canvas

查看:36
本文介绍了在 Flutter Canvas 中使用 Gradient 和 Paint 对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用以下示例绘制一个半圆:Flutter如何画半圆(半圆)

I am able to draw a semi circle using the following example: Flutter how to draw semicircle (half circle)

然而,Paint 对象似乎只接受 Color(使用 Paint.color).我想添加一个 RadialGradientLinearGradient 作为 Color.这可能吗?

However, the Paint object only seems to accept a Color (using Paint.color). I would like to add a RadialGradient or LinearGradient as the Color. Is that possible?

推荐答案

是的!这完全可以使用 Paint.shader.
您可以直接使用 dart:ui 创建渐变着色器,也可以使用
Gradient.createShader.

Yes! This is totally possible using Paint.shader.
You can either create a gradient shader directly using dart:ui or convert a Flutter gradient to a shader using Gradient.createShader.

import 'dart:ui' as ui;

// In your paint method
final paint = Paint()
  ..shader = ui.Gradient.linear(
    startOffset,
    endOffset,
    [
      color1,
      color2,
    ],
  );

一个真实的例子可以是 看到这里.

A real world example can be seen here.

import 'package:flutter/painting.dart';

// In your paint method
final paint = Paint()
  ..shader = RadialGradient(
    colors: [
      color1,
      color2,
    ],
  ).createShader(Rect.fromCircle(
    center: offset,
    radius: radius,
  ));

这方面的一个例子可以是 在这里找到.

An example of this can be found here.

这两者实际上是相同的.当您调用 createShader 时,Flutter 绘画版本只是将其转换为 dart:ui 渐变(shader).它存在的原因是绘画版本更适合像 Container 这样的预构建小部件.

These two are effectively the same. The Flutter painting version simply converts it to a dart:ui gradient (shader) when you call createShader. The reason it exists is that the painting version is better suited for prebuilt widgets like Container.

这篇关于在 Flutter Canvas 中使用 Gradient 和 Paint 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆