The default color from a Slider on Xamarin Mac project is blue, I want to change it to green, So I have made a Custom Renderer, but unfortunately, I don't what to do inside the custom renderer, How can I change the color?
using CustomSliderColor.MacOS;
using Xamarin.Forms;
using Xamarin.Forms.Platform.MacOS;
[assembly: ExportRenderer(typeof(CustomSlider), typeof(CustomSliderRenderer))]
namespace CustomSliderColor.MacOS
{
public class CustomSliderRenderer : SliderRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Slider> e)
{
base.OnElementChanged(e);
if (Control != null)
{
//What do I put here?????
}
}
}
}
I found an answer to my own question.
First subclass the "NSSliderCell" class, here an example:
using System;
using AppKit;
using CoreGraphics;
using Foundation;
namespace myproject.MacOs
{
public class CustomSliderCell : NSSliderCell
{
public override void DrawBar(CGRect aRect, Boolean flipped)
{
CGRect rect = aRect;
rect.Size = new CGSize(rect.Size.Width, 5);
float barRadius = 2.5f;
double value = (double)((this.DoubleValue - this.MinValue) / (this.MaxValue - this.MinValue));
float finalWidth = (float)(value * (this.ControlView.Frame.Size.Width - 8));
CGRect leftRect = rect;
leftRect.Size = new CGSize(finalWidth, leftRect.Size.Height);
NSBezierPath bg = new NSBezierPath();
bg.AppendPathWithRoundedRect(rect, barRadius, barRadius);
NSColor.FromRgb(0, 160, 0).SetFill();
bg.Fill();
NSBezierPath active = new NSBezierPath();
active.AppendPathWithRoundedRect(leftRect, barRadius, barRadius);
NSColor.FromRgb(0,128,0).SetFill();
active.Fill();
}
}
}
Then in your customSlider renderer on Mac
using AppKit;
using CustomSliderColor.MacOS;
using Xamarin.Forms;
using myproject;
using myproject.MacOs;
using Xamarin.Forms.Platform.MacOS;
[assembly: ExportRenderer(typeof(CustomSlider), typeof(CustomSliderRenderer))]
namespace CustomSliderColor.MacOS
{
public class CustomSliderRenderer : SliderRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Slider> e)
{
if (Control == null)
{
NSSlider customNSSlider = new NSSlider();
CustomSliderCell custom = new CustomSliderCell();
customNSSlider.Cell = custom;
SetNativeControl(customNSSlider);
}
base.OnElementChanged(e);
}
}
}
And then you have it!!!