live-chart icon indicating copy to clipboard operation
live-chart copied to clipboard

Add an abstract base class for chart background

Open ogoshen opened this issue 5 months ago • 1 comments

Allows for using custom backgrounds on charts. Like the one below with rounded corners, related to https://github.com/lcallarec/live-chart/issues/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();
        }
    }
}

ogoshen avatar Jul 19 '25 17:07 ogoshen