Skip to content

Add an abstract base class for chart background#53

Open
ogoshen wants to merge 1 commit intolcallarec:masterfrom
ogoshen:rounded_background
Open

Add an abstract base class for chart background#53
ogoshen wants to merge 1 commit intolcallarec:masterfrom
ogoshen:rounded_background

Conversation

@ogoshen
Copy link

@ogoshen ogoshen commented Jul 19, 2025

Allows for using custom backgrounds on charts.
Like the one below with rounded corners, related to #27.

using Cairo;

namespace LiveChart {

    class ChartRoundedBackground : LiveChart.AbstractBackground {

        private ChartRoundedBackgroundDrawer drawer = new ChartRoundedBackgroundDrawer();

        public ChartRoundedBackground(double radius = 6) {
            this.radius = radius;
        }

        public double radius { get; set; }

        public override bool visible { get; set; default = true; }

        public Gdk.RGBA color {
            get {
                return main_color;
            }
            set {
                main_color = value;
            }
        }

        [Version(deprecated = true, deprecated_since = "1.8.0", replacement = "Background.color")]
        public override Gdk.RGBA main_color {
            get; set; default = Gdk.RGBA() {
                red = 0.1f,
                green = 0.1f,
                blue = 0.1f,
                alpha = 1.0f
            };
        }

        public override void draw(Context ctx, LiveChart.Config config) {
            if (visible) {
                drawer.draw(ctx, config, this.color, this.radius);
            }
        }
    }

    class ChartRoundedBackgroundDrawer : Object {

        // https://www.cairographics.org/cookbook/roundedrectangles/
        void rounded_rec(Cairo.Context ctx, double x, double y, double w, double h, double r) {
            ctx.new_sub_path();
            ctx.arc(r, r, r, Math.PI, 3 * Math.PI / 2);
            ctx.arc(w - r, r, r, 3 * Math.PI / 2, 2 * Math.PI);
            ctx.arc(w - r, h - r, r, 0, Math.PI / 2);
            ctx.arc(r, h - r, r, Math.PI / 2, Math.PI);
            ctx.close_path();
        }

        public void draw(Cairo.Context ctx, LiveChart.Config config, Gdk.RGBA color, double radius) {
            rounded_rec(ctx, 0, 0, config.width, config.height, radius);
            ctx.clip_preserve();
            ctx.set_source_rgba(color.red, color.green, color.blue, 0.03f);
            ctx.fill_preserve();
            ctx.set_source_rgba(color.red, color.green, color.blue, color.alpha);
            ctx.stroke();
        }
    }
}

@stsdc
Copy link
Contributor

stsdc commented Jul 19, 2025

Hi @ogoshen, would you mind opening a PR also in here: https://github.com/elementary/live-chart/?
I'm interested in rounded corners 😄

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants