Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Gradient with Paint object in Flutter Canvas

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

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?

like image 234
user2511882 Avatar asked Feb 01 '20 18:02

user2511882


People also ask

How do you add gradient in custom paint Flutter?

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

How do you add a gradient to a canvas color?

The addColorStop() method specifies the color stops, and its position along the gradient. Gradient positions can be anywhere between 0 to 1. To use the gradient, set the fillStyle or strokeStyle property to the gradient, then draw the shape (rectangle, text, or a line).

How do you make a radial gradient in Flutter?

You need to use the center property of the RadialGradient to position the gradient. Use the code below and it should give you the same design in Flutter as the CSS code: gradient: RadialGradient( center: Alignment(-0.8, -0.6), colors: [ Color. fromRGBO(3, 235, 255, 1), Color.


1 Answers

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.

dart:ui gradient

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.

Flutter painting gradient

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.


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.

like image 94
creativecreatorormaybenot Avatar answered Sep 17 '22 22:09

creativecreatorormaybenot