在Xamarin.Forms中自定义进度条外观

时间:2018-02-09 10:21:05

标签: c# ios xamarin xamarin.forms

我使用Drawable自定义了ProgressBarAndroid的呈现,并回复了this question,但该解决方案无法与iOS配合使用。

以下是Android呈现的方式。 enter image description here

以下是iOS呈现的方式 enter image description here

以下是我的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;
    }
}

}

我如何做到这一点?

1 个答案:

答案 0 :(得分:5)

根据@ SushiHangover的回答,我们可以ViewRenderer来实现您的效果。

首先,创建我们自己的ProgressView,确保它继承自ContentView。还要添加BindableProperty来显示值:

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);

    ...
}

然后,我们可以将自定义渲染器设为:

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;
    }
}

因为这是在渲染器中,我们应该刷新标签的框架:

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

最后我们可以在表格上使用它:

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