创建一个使用CAGradientLayer作为其层的UIView子类

时间:2014-11-10 10:44:26

标签: c# ios xamarin.ios xamarin cagradientlayer

我想将this移植到C#。

我不知道如何转换它:

@property (nonatomic, strong, readonly) CAGradientLayer *layer;

layer是UIView的默认图层。 Xamarin已经拥有Layer属性。我该怎么覆盖这个?我需要覆盖吗?

我也尝试了

public CAGradientLayer layer { [Export ("Layer")] get; [Export ("Layer:")] set; }

但如果我想设置图层的颜色,应用程序崩溃(System.Reflection.TargetInvocationException - 出列单元格时出现NullReferenceException)。此外,它应该是只读的。

然后我在documentation中看到了如何转换它:

public class BlueView : UIView
{
    [Export ("layerClass")]
    public static Class GetLayerClass ()
    {
        return new Class (typeof (BlueLayer));
    }

    public override void Draw (RectangleF rect)
    {
        // Do nothing, the Layer will do all the drawing
    }
}

public class BlueLayer : CALayer
{
    public override void DrawInContext (CGContext ctx)
    {
        ctx.SetFillColor (0, 0, 1, 1);
        ctx.FillRect (Bounds);
    }
}

这对我没有帮助,因为我需要像 SetFillColors 这样的东西,以便我可以使用CGColor[]数组。但是没有这样的功能。

如何在C#with Monotouch中使用我的自定义UIView创建CAGradientLayer

1 个答案:

答案 0 :(得分:3)

这篇精彩的帖子(iOS Programming Recipe 20: Using CAGradientLayer In A Custom View)向我指出了正确的方向:

using System;
using System.Drawing;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using MonoTouch.CoreAnimation;
using MonoTouch.CoreGraphics;
using MonoTouch.ObjCRuntime;

namespace SampleApp
{
    public class GradientView : UIView
    {
//      public new CAGradientLayer Layer { get; private set; }
        private CAGradientLayer gradientLayer {
            get { return (CAGradientLayer)this.Layer; }
        }

        public GradientView ()
        {
        }


        [Export ("layerClass")]
        public static Class LayerClass ()
        {
            return new Class (typeof(CAGradientLayer));
        }

        public void setColors(CGColor[] colors){
            this.gradientLayer.Colors = colors;
        }

//      public override void Draw (RectangleF rect)
//      {
//          // Do nothing, the Layer will do all the drawing
//      }
    }
}

在这里,我创建并设置了我的背景视图:

GradientView background = new GradientView ();
background.setColors (new CGColor[] {
    UIColor.FromRGB (18,200,45).CGColor,
    UIColor.White.CGColor,
    UIColor.White.CGColor
});

现在似乎有效。使用自定义属性(包含强制转换)和单独的方法可以解决问题。当然你可以写一个完整的访问者。这是一个简单的测试。

相关问题