简体   繁体   English

如何使用Xamarin.Forms在iOS中创建带圆角的进度条

[英]How to create a progress bar with rounded corners in iOS using Xamarin.Forms

I used inputs from this SO Question to create a custom progress-bar with rounded corners for the Android platform using the Drawable . 我使用来自此SO问题的输入,使用DrawableAndroid平台创建一个带圆角的自定义进度条。 But the I'm not able to create the same output for the iOS . 但是我无法为iOS创建相同的输出。

Given below is how it looks on Android . 以下是它在Android外观。 Android示例

How can I create the same effect in the iOS as well? 如何在iOS创建相同的效果?

There are a number of ways to do this, I prefer using the CALayer of a UIView and adding a CAShapeLayer that draws the "progress bar". 有很多方法可以做到这一点,我更喜欢使用UIViewCALayer并添加一个绘制“进度条”的CAShapeLayer

UIView ProgressBar Example: UIView ProgressBar示例:

在此输入图像描述

public class ProgressView : UIView
{
    CAShapeLayer progressLayer;
    UILabel label;

    public ProgressView() { Setup(); }
    public ProgressView(Foundation.NSCoder coder) : base(coder) { Setup(); }
    public ProgressView(Foundation.NSObjectFlag t) : base(t) { Setup(); }
    public ProgressView(IntPtr handle) : base(handle) { }
    public ProgressView(CGRect frame) : base(frame) { Setup(); }

    void Setup()
    {
        BackgroundColor = UIColor.Clear;

        Layer.CornerRadius = 25;
        Layer.BorderWidth = 10;
        Layer.BorderColor = UIColor.Blue.CGColor;
        Layer.BackgroundColor = UIColor.Cyan.CGColor;

        progressLayer = new CAShapeLayer()
        {
            FillColor = UIColor.Red.CGColor,
            Frame = Bounds
        };
        Layer.AddSublayer(progressLayer);

        label = new UILabel(Bounds)
        {
            TextAlignment = UITextAlignment.Center,
            TextColor = UIColor.White,
            BackgroundColor = UIColor.Clear,
            Font = UIFont.FromName("ChalkboardSE-Bold", 20)
        };
        InsertSubview(label, 100);
    }

    double complete;
    public double Complete
    {
        get { return complete; }
        set { complete = value; label.Text = $"{value * 100} %"; SetNeedsDisplay(); }
    }

    public override void Draw(CGRect rect)
    {
        base.Draw(rect);
        var progressWidth = (rect.Width - (Layer.BorderWidth * 2)) * complete;
        var progressRect = new CGRect(rect.X + Layer.BorderWidth, rect.Y + Layer.BorderWidth, progressWidth, (rect.Height - Layer.BorderWidth * 2));
        progressLayer.Path = UIBezierPath.FromRoundedRect(progressRect, 25).CGPath;
    }
}

Usage Example: 用法示例:

var progressView = new ProgressView(new CGRect(50, 50, 300, 50));
Add(progressView);
DispatchQueue.MainQueue.DispatchAsync(async () =>
{
    while (progressView.Complete <= 1)
    {
        InvokeOnMainThread(() => progressView.Complete += 0.05);
        await Task.Delay(1000);
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM