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

标签 c# ios xamarin.ios xamarin cagradientlayer

我要移植 this到 C#。

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

@property (nonatomic, strong, readonly) CAGradientLayer *layer;
layer是 UIView 的默认层。 Xamarin 已经有一个 Layer属性(property)。我该如何覆盖这个?我需要覆盖它吗?

我也试过了
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[]大批。但是没有这样的功能。

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

最佳答案

这篇精彩的帖子 (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
//      }
    }
}

在这里我创建并设置了我的背景 View :
GradientView background = new GradientView ();
background.setColors (new CGColor[] {
    UIColor.FromRGB (18,200,45).CGColor,
    UIColor.White.CGColor,
    UIColor.White.CGColor
});

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

关于c# - 创建一个使用 CAGradientLayer 作为其层的 UIView 子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26841904/

相关文章:

ios - dismissViewControllerAnimated() 不会关闭 View Controller

validation - Monotouch 用户输入数据验证

xamarin - 对于现有 Android 应用程序,我应该选择 Xamarin native 还是 Xamarin.Forms?

uitableview - 以编程方式添加到 UITableViewCell 的 UIButtons 永远不会出现

c# - 如何在 C# 项目中构建具有自定义文件扩展名的 DLL?

c# - 获取类型的默认值

ios - 如何将生成的音频保存到 iOS 中的文件中?

ios - 使用 openURL 的 '#' 结尾

c# - 如何使用 GTKSharp 打印图像

c# - 如何从 StackOverflow API *creation_date* 字段中检索实际日期?