简体   繁体   中英

iOS tab bar background image propgrammatically

I want to make a separator between items in my tabor programmatically. Then I wrote this code but it display nothing.

        float separator_width = 3f;
        UIColor separator_color = UIColor.Red;

        float itemWidth = (float)Math.Floor(this.TabBar.Frame.Width / this.TabBar.Items.Length);

        UIView bgView = new UIView();
        bgView.Frame = new CGRect(0, 0, this.TabBar.Frame.Width, this.TabBar.Frame.Height);

        for (int i = 0; i < this.TabBar.Items.Length; i++)
        {
            UIView separator = new UIView();
            separator.Frame = new CGRect(itemWidth * (i + 1) - separator_width / 2, 0, separator_width, this.TabBar.Frame.Height);
            bgView.Add(separator);
        }

        UIGraphics.BeginImageContext(new CGSize(bgView.Frame.Width, bgView.Frame.Height));

        bgView.Layer.RenderInContext(UIGraphics.GetCurrentContext());

        UIImage tabBarBackground = UIGraphics.GetImageFromCurrentImageContext();

        UIGraphics.EndImageContext();



        UITabBar.Appearance.BackgroundImage = tabBarBackground;

I tried to write it and display it in another view but still nothing. What can I do ?

Thanks

I found another solution. For these who search for that :

Check out below :

        var image = new UIImage();
        var path = new UIBezierPath();
        var lineHeight = 42.5f;
        float itemWidth = (float)Math.Floor(this.TabBar.Frame.Width / this.TabBar.Items.Length);

        UIGraphics.BeginImageContextWithOptions(new CGSize(this.TabBar.Frame.Width, this.TabBar.Frame.Height), false, 0);

        image.Draw(new CGPoint(0,0));

        UIColor.Clear.FromHex(0xF2F2F2).SetStroke();
        path.LineWidth = 1;


        for (int i = 1; i < this.TabBar.Items.Length; i++)
        {
            path.MoveTo(new CGPoint(itemWidth * i - path.LineWidth / 2, (this.TabBar.Frame.Height - lineHeight) / 2));
            path.AddLineTo(new CGPoint(itemWidth * i - path.LineWidth / 2, lineHeight + (this.TabBar.Frame.Height - lineHeight) / 2));
        }

        path.Stroke();
        image = UIGraphics.GetImageFromCurrentImageContext();
        UIGraphics.EndImageContext();

        UITabBar.Appearance.BackgroundImage = image;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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