Customizing a Progress Bar appearance in Xamarin.Forms

拥有回忆 提交于 2020-08-22 09:58:45

问题


I used Drawable to customize the rendering of the ProgressBar in Android as answered to this question but the solution is not working with iOS.

Below is how it renders in Android.

Below is how it renders in iOS

Below is the code for my iOS CustomRenderer

[assembly: ExportRenderer(typeof(CustomProgressbar), typeof(CustomProgressBarRenderer))]
namespace Demo.iOS.Renderers
{
public class CustomProgressBarRenderer : ProgressBarRenderer
{
    protected override void OnElementChanged(ElementChangedEventArgs<ProgressBar> e)
    {
        try
        {
            base.OnElementChanged(e);

            if (Control != null)
            {                
               Control.ProgressTintColor = Color.FromHex("#ff0000").ToUIColor();                       
               Control.TrackTintColor = Color.FromHex("#3489cc").ToUIColor();
             } 
        }
        catch (Exception ex)
        {

        }
    }

    public override void LayoutSubviews()
    {
        base.LayoutSubviews();
        var X = 1.0f;
        var Y = 15.0f;
        CGAffineTransform _transform = CGAffineTransform.MakeScale(X, Y);
        this.Transform = _transform;
        this.ClipsToBounds = true;
        this.Layer.MasksToBounds = true;
        this.Layer.CornerRadius = 5;
    }
}

}

How do I accomplish this?


回答1:


According to @SushiHangover's answer, we can make a ViewRenderer to achieve your effect.

Firstly, create our own ProgressView, make sure it is inherited from ContentView. also add a BindableProperty to present the value:

public partial class ProgressView : ContentView
{
    public double Progress
    {
        set { SetValue(ProgressProperty, value); }
        get { return (double)GetValue(ProgressProperty); }
    }

    public readonly static BindableProperty ProgressProperty = BindableProperty.Create("Progress", typeof(double), typeof(ProgressView), 0.0);

    ...
}

Then, We can make the Custom renderer like:

protected override void OnElementChanged(ElementChangedEventArgs<View> e)
{
    base.OnElementChanged(e);

    //You can refer to @SushiHangover's method for detail's code, here I use the same name.
    Setup();
    Complete = ((ProgressView)Element).Progress;
}

protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
    base.OnElementPropertyChanged(sender, e);

    if (e.PropertyName == "Progress")
    {
        Complete = ((ProgressView)Element).Progress;
    }
}

Because this is in renderer, we should refresh our label's frame:

public override void Draw(CGRect rect)
{
    base.Draw(rect);
    ...
    label.Frame = Bounds;
}

At last we can use it on Forms like:

<local:ProgressView x:Name="MyProgress" HeightRequest="50"/>


来源:https://stackoverflow.com/questions/48703637/customizing-a-progress-bar-appearance-in-xamarin-forms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!