1

我想将它移植C#。

我不知道我应该如何转换它:

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

layer是 UIView 的默认层。Xamarin 已经拥有一个Layer属性。我该如何覆盖这个?我需要覆盖它吗?

我也试过了

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

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

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

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[]数组。但是没有这样的功能。

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

4

1 回答 1

3

这篇精彩的帖子(iOS 编程秘籍 20:在自定义视图中使用 CAGradientLayer)为我指明了正确的方向:

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

现在它似乎工作了。使用自定义属性(包含强制转换)和单独的方法就可以了。当然你可以写一个完整的访问器。这是一个简单的测试。

于 2014-11-10T12:18:43.167 回答