user2511882
user2511882

Reputation: 9152

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?

Upvotes: 34

Views: 25058

Answers (2)

user3249027
user3249027

Reputation: 540

Note: both approaches aren’t quite the same. For a diagonal gradient with the second approach, you’ll need to transform it, since Gradient.createShader(Rect rect)demands a rect;

final diagonalVector = Offset(x - x1, y - y1); // Vector pointing from start to target point.

paint.shader = LinearGradient(
  colors: [
    from,
    to,
  ],
  transform:  // Rotate gradient to align with the diagonal
      GradientRotation(atan2(diagonalVector.dy, diagonalVector.dx)),
).createShader(Rect.fromPoints(
  Offset(x1, y1),
  Offset(x, y),
));

Upvotes: 0

creativecreatorormaybenot
creativecreatorormaybenot

Reputation: 126964

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.

Upvotes: 88

Related Questions