Ejemplo n.º 1
0
		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();

			TKChart chart = new TKChart (this.View.Bounds);
			chart.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight;
			this.View.AddSubview (chart);

			string[] months = new string[]{ "Jan", "Feb", "Mar", "Apr", "May", "Jun" };
			int[] values = new int[]{ 95, 40, 55, 30, 76, 34 };
			List<TKChartDataPoint> list = new List<TKChartDataPoint> ();

			for (int i = 0; i < months.Length; i++) {
				list.Add (new TKChartDataPoint(new NSString(months[i]), new NSNumber(values[i])));
			}
			chart.AddSeries (new TKChartAreaSeries (list.ToArray()));

			CALayer layer = new CALayer ();
			layer.Bounds = new RectangleF (0, 0, 100, 100);
			layer.BackgroundColor = new UIColor(1, 0, 0, 0.6f).CGColor;
			layer.ShadowRadius = 10;
			layer.ShadowColor = UIColor.Yellow.CGColor;
			layer.ShadowOpacity = 1;
			layer.CornerRadius = 10;

			TKChartLayerAnnotation a = new TKChartLayerAnnotation(layer, new NSString("Mar"), new NSNumber(80), chart.Series[0]);
			a.ZPosition = TKChartAnnotationZPosition.AboveSeries;
			chart.AddAnnotation(a);
		}
 public OuterShadow(CALayer targetLayer, SizeF frameSize, float shadowDepth)
 {
     this.targetLayer = targetLayer;
     FrameSize = frameSize;
     ShadowDepth = shadowDepth;
     shadows[Edge.Top] = shadows[Edge.Right] = shadows[Edge.Bottom] = shadows[Edge.Left] = null;
 }
		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();
			View.BackgroundColor = UIColor.White;
			View.UserInteractionEnabled = true;

			layer = new CALayer {
				Bounds = new CGRect (0, 0, 50, 50),
				Position = new CGPoint (50, 50),
				Contents = UIImage.FromFile ("monkey2.png").CGImage,
				ContentsGravity = CALayer.GravityResize,
				BorderWidth = 1.5f,
				BorderColor = UIColor.Green.CGColor
			};

			View.Layer.AddSublayer (layer);

			View.AddGestureRecognizer (new UITapGestureRecognizer (() => {
				ViewController initalViewController = (ViewController)MainStoryboard.InstantiateViewController("InitalViewController");

				initalViewController.ModalTransitionStyle = UIModalTransitionStyle.FlipHorizontal;

				PresentViewController(initalViewController, true, null);
			}));
		}
		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();

			sessionManager = new SessionManager ();
			sessionManager.StartRunning ();

			previewLayer = new AVCaptureVideoPreviewLayer (sessionManager.CaptureSession) {
				Frame = previewView.Bounds,
				VideoGravity = AVLayerVideoGravity.ResizeAspectFill
			};

			if (previewLayer.Connection != null && previewLayer.Connection.SupportsVideoOrientation)
				previewLayer.Connection.VideoOrientation = AVCaptureVideoOrientation.LandscapeLeft;
			previewView.Layer.AddSublayer (previewLayer);
			previewView.Layer.MasksToBounds = true;

			barcodeTargetLayer = new CALayer () {
				Frame = View.Layer.Bounds
			};
			View.Layer.AddSublayer (barcodeTargetLayer);

			synth = new Synth ();
			synth.LoadPreset (this);
		}
Ejemplo n.º 5
0
		public static void Draw(CALayer target, IViewport viewport, IStyle style, IFeature feature)
		{
			const string styleKey = "laag";

			if(feature[styleKey] == null) feature[styleKey] = ToiOSBitmap(feature.Geometry);

			var bitmap = (UIImage)feature [styleKey];

			var dest = WorldToScreen(viewport, feature.Geometry.GetBoundingBox());
			dest = new BoundingBox(
				dest.MinX,
				dest.MinY,
				dest.MaxX,
				dest.MaxY);

			var destination = RoundToPixel(dest);

			var tile = new CALayer
			{
				Frame = destination,
				Contents = bitmap.CGImage,
			};
			
			target.AddSublayer(tile);
		}
Ejemplo n.º 6
0
        public static void PositionMultiPolygon(CALayer shape, MultiPolygon multiPolygon, IStyle style, IViewport viewport)
        {
            var shapeLayer = shape as CAShapeLayer;
            var path = multiPolygon.ToUIKit(viewport);
            //var frame = ConvertBoundingBox (multiPolygon.GetBoundingBox(), viewport);
            shapeLayer.Path = path.CGPath;
            //shape.Frame = frame;
            /*
            if (viewport.Resolution > MinResolution || viewport.Resolution < MaxResolution) {
                //recalculate
                var newImage = RenderMultiPolygonOnLayer (multiPolygon, style, viewport);

                shape.Contents = newImage.Contents;
                shape.Frame = newImage.Frame;

                var resolution = ZoomHelper.ClipResolutionToExtremes (Resolutions, viewport.Resolution);

                MinResolution = ZoomHelper.ZoomOut (Resolutions, resolution);
                MaxResolution = ZoomHelper.ZoomIn (Resolutions, resolution);

            } else {
                //reposition Geometry
                var frame = ConvertBoundingBox (multiPolygon.GetBoundingBox(), viewport);
                var newFrame = new RectangleF (frame.X, (frame.Y), frame.Width, frame.Height);

                shape.Frame = newFrame;
                //shape.Frame = frame;
            }
            */
        }
Ejemplo n.º 7
0
		protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
		{
			base.OnElementChanged(e);

			if (e.NewElement != null && !isInitialized)
			{
				var formsEntry = e.NewElement as LoginEntry;
				formsEntry.FontFamily = "SegoeUI-Light";
				formsEntry.TextColor = Color.FromHex("#778687");
				formsEntry.FontSize = 18;

				nativeTextField = Control as UITextField;
				nativeTextField.BorderStyle = UITextBorderStyle.None;

				//Figure out how to reference font from Resources as Embedded Resource
				if (!String.IsNullOrEmpty(formsEntry.Placeholder))
					nativeTextField.AttributedPlaceholder = new NSAttributedString(formsEntry.Placeholder, UIFont.FromName("SegoeUI-Light", 18), Color.FromHex("#778687").ToUIColor());

				bottomBorder = new CALayer();
				bottomBorder.BackgroundColor = Color.FromHex("#778687").ToCGColor();
				Control.Layer.AddSublayer(bottomBorder);

				isInitialized = true;
			}
		}
		public static void AddBorder(this UIView view, UIRectEdge edge, UIColor color, nfloat thickness) {

			var border = new CALayer ();
			var f = view.Frame;
			switch(edge)
			{
			case UIRectEdge.Top:
				border.Frame = new CGRect(0, 0, f.Width, thickness);
				break;
			case UIRectEdge.Bottom:
				border.Frame = new CGRect (0, f.Height - thickness, f.Width, thickness);
				break;
			case UIRectEdge.Left:
				border.Frame = new CGRect(0, 0, thickness, f.Height);
				break;
			case UIRectEdge.Right:
				border.Frame = new CGRect(f.Width - thickness, 0, thickness, f.Height);
				break;
			default:
				break;
			}

			border.BackgroundColor = color.CGColor;
			view.Layer.AddSublayer (border);
		}
		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();

			sessionManager = new SessionManager ();
			sessionManager.StartRunning ();

			previewLayer = new AVCaptureVideoPreviewLayer (sessionManager.CaptureSession) {
				Frame = previewView.Bounds,
				VideoGravity = AVLayerVideoGravity.ResizeAspectFill
			};

			if (previewLayer.Connection != null && previewLayer.Connection.SupportsVideoOrientation)
				previewLayer.Connection.VideoOrientation = AVCaptureVideoOrientation.LandscapeLeft;
			previewView.Layer.AddSublayer (previewLayer);
			previewView.Layer.MasksToBounds = true;

			barcodeTargetLayer = new CALayer () {
				Frame = View.Layer.Bounds
			};
			View.Layer.AddSublayer (barcodeTargetLayer);

			synth = new Synth ();
			synth.LoadPreset (this);

			// the loop that continuously looks for barcodes to detect
			stepTimer = NSTimer.CreateScheduledTimer (0.15, this, new Selector ("step:"), null, true);
		}
Ejemplo n.º 10
0
        public ShimmeringMaskLayer()
        {
            FadeLayer = new CALayer();
            FadeLayer.BackgroundColor = UIColor.White.CGColor;
            AddSublayer(FadeLayer);

            RemoveAllAnimations();
        }
Ejemplo n.º 11
0
		public override void Clone (CALayer other)
		{
			CircleLayer o = (CircleLayer) other;
			Radius = o.Radius;
			Color = o.Color;
			Thickness = o.Thickness;
			base.Clone (other);
		}
Ejemplo n.º 12
0
        public override void AwakeFromNib()
        {
            base.AwakeFromNib();

			View.Layer = new CALayer();
			View.WantsLayer = true;

			textContainer = new CALayer();
			textContainer.AnchorPoint = CGPoint.Empty;
			textContainer.Position = new CGPoint(10, 10);
			textContainer.ZPosition = 100;
			textContainer.BackgroundColor = NSColor.Black.CGColor;
			textContainer.BorderColor = NSColor.White.CGColor;
			textContainer.BorderWidth = 2;
			textContainer.CornerRadius = 15;
			textContainer.ShadowOpacity = 0.5f;
			View.Layer.AddSublayer(textContainer);

			textLayer = new CATextLayer();
			textLayer.AnchorPoint = CGPoint.Empty;
			textLayer.Position = new CGPoint(10, 6);
			textLayer.ZPosition = 100;
			textLayer.FontSize = 24;
			textLayer.ForegroundColor = NSColor.White.CGColor;
			textContainer.AddSublayer(textLayer);

			// Rely on setText: to set the above layers' bounds: [self setText:@"Loading..."];
			SetText("Loading...", textLayer);


			var dirs = NSSearchPath.GetDirectories(NSSearchPathDirectory.LibraryDirectory, NSSearchPathDomain.Local);
			foreach (string dir in dirs) {
				Console.WriteLine("Dir: {0}", dir);
			}
			string libDir = dirs[0];
			string desktopPicturesDir = Path.Combine(libDir, "Desktop Pictures");
			Console.WriteLine("DP Dir: {0}", desktopPicturesDir);

			// Launch loading of images on background thread
			Task.Run(async () => {
				await AddImagesFromFolderUrlAsync(desktopPicturesDir);
			});

			repositionButton.Layer.ZPosition = 100;
			durationTextField.Layer.ZPosition = 100;
			lastWindowSize = Window.Frame.Size;

			Window.DidResize += (sender, e) => {
				if (Math.Abs(lastWindowSize.Width - Window.Frame.Width) > 25 || Math.Abs(lastWindowSize.Height - Window.Frame.Height) > 25) {
					windowIsResizing = true;
					repositionImages(repositionButton);
					lastWindowSize = Window.Frame.Size;
					windowIsResizing = false;
				}
			};

        }
 public override void Clone(CALayer other)
 {
     RoundProgressLayer o = (RoundProgressLayer) other;
     Progress = o.Progress;
     StartAngle = o.StartAngle;
     TintColor = o.TintColor;
     TrackColor = o.TrackColor;
     base.Clone (other);
 }
        private void MaskImageWithImage(UIImageView imgView, UIImage maskImage)
        {
            var aMaskLayer = new CALayer();

            aMaskLayer.Frame = new CGRect(0, 0, imgView.Image.Size.Width, imgView.Image.Size.Height);
            aMaskLayer.Contents = maskImage.CGImage;

            imgView.Layer.Mask = aMaskLayer;
        }
Ejemplo n.º 15
0
		public static List<IFeature> RenderStackedLabelLayer(IViewport viewport, BasicLayer layer)
		{
			lock(_syncRoot)
			{
				var renderedFeatures = new List<IFeature> ();
				var canvas = new CALayer ();
				canvas.Opacity = (float)layer.Opacity;

				//todo: take into account the priority 
				var features = layer.GetFeaturesInView (viewport.Extent, viewport.Resolution);
				var margin = viewport.Resolution * 15;

				var clusters = new List<Cluster> ();
				//todo: repeat until there are no more merges
				ClusterFeatures (clusters, features, margin, null, viewport, viewport.Resolution);
				//CenterClusters (clusters);

				//CATransaction.Begin();
				//CATransaction.SetValueForKey (MonoTouch.Foundation.NSNumber.FromBoolean(true), CATransaction.DisableActionsKey);

				foreach(var cluster in clusters){

					var feature = cluster.Features.OrderBy(f => f.Geometry.GetBoundingBox().GetCentroid().Y).FirstOrDefault();
					//SetFeatureOutline (feature, layer.LayerName, cluster.Features.Count);
					//var bb = RenderBox(cluster.Box, viewport);

					//Zorg dat dit ALTIJD decimal zelfde ISet als ViewChanged is
					//var feature = cluster.Features.FirstOrDefault ();

					var styles = feature.Styles ?? Enumerable.Empty<IStyle>();
					foreach (var style in styles)
					{
						if (feature.Styles != null && style.Enabled)
						{
							var styleKey = layer.LayerName; //feature.GetHashCode ().ToString ();
							var renderedGeometry = (feature[styleKey] != null) ? (CALayer)feature[styleKey] : null;

							if (renderedGeometry == null) {
								renderedGeometry = GeometryRenderer.RenderPoint (feature.Geometry as Mapsui.Geometries.Point, style, viewport);

								feature [styleKey] = renderedGeometry;
								feature ["first"] = true;

							} else {
								feature ["first"] = false;
							}
						}
					}
					renderedFeatures.Add (feature);

					//renderedFeatures.Add (bb);
				}

				return renderedFeatures;
			}
		}
Ejemplo n.º 16
0
		private CALayer SetupLayers()
		{
			backgroundLayer = SetupBackgroundLayer ();
			
			backgroundLayer.AddSublayer (SetupClockFaceLayer ());
			backgroundLayer.AddSublayer (SetupBorderLayer ());
			backgroundLayer.AddSublayer (SetupGlossyLayer ());

			return backgroundLayer;
		}
Ejemplo n.º 17
0
        internal static void ConfigLayerHighRes(CALayer layer)
        {
            if (!HighRes)
                return;

            if (sscale == null)
                sscale = new Selector ("setContentsScale:");

            Messaging.void_objc_msgSend_float (layer.Handle, sscale.Handle, 2.0f);
        }
Ejemplo n.º 18
0
		public SourceView (CGRect r) : base (r)
		{
			// Set the background color of the view to Red
			var layer = new CALayer {
				BackgroundColor = new CGColor (1f, 0f, 0f)
			};

			WantsLayer = true;
			Layer = layer;
		}
Ejemplo n.º 19
0
        public GradientLayer(GradientLayerType type, GradientLayerAreaType segment)
        {
            _type = type;
            _segment = segment;

            _minimumOpacity = 0f;

            _gradientMaskLayer = CALayer.Create ();
            _gradientMaskLayer.ContentsScale = UIScreen.MainScreen.Scale;

            _gradientLayer = new CAGradientLayer ();
            _gradientLayer.Frame = this.Bounds;
            _gradientLayer.Mask = _gradientMaskLayer;

            this.MasksToBounds = true;
            this.AddSublayer (_gradientLayer);
            this.ContentsScale = UIScreen.MainScreen.Scale;

            if (_type == GradientLayerType.Face)
            {
                _gradientLayer.Colors = colors1;
                _gradientLayer.Locations = locations1;

                _maximumOpacity = .75f;
            }
            else
            {
                _gradientLayer.Colors = colors2;
                _gradientLayer.Locations = locations2;

                _maximumOpacity = 1f;
            }

            if (_segment == GradientLayerAreaType.Top)
            {
                this.ContentsGravity = "bottom";

                _gradientLayer.StartPoint = new PointF (0, 0);
                _gradientLayer.EndPoint = new PointF (0, 1);

                _gradientMaskLayer.ContentsGravity = "bottom";
            }
            else
            {
                this.ContentsGravity = "top";

                _gradientLayer.StartPoint = new PointF (0, 1);
                _gradientLayer.EndPoint = new PointF (0, 0);

                _gradientMaskLayer.ContentsGravity = "top";
            }

            _gradientLayer.Opacity = _minimumOpacity;
        }
Ejemplo n.º 20
0
		public DestView (CGRect r) : base (r)
		{

			// Set the background color of this view to Green
			var layer = new CALayer {
				BackgroundColor = new CGColor (0f, 1f, 0f)
			};

			WantsLayer = true;
			Layer = layer;
		}
Ejemplo n.º 21
0
		void DrawBorder (MyEntry view)
		{
			var borderLayer = new CALayer ();
			borderLayer.MasksToBounds = true;
			borderLayer.Frame = new CoreGraphics.CGRect (0f, Frame.Height / 2, Frame.Width, 1f);
			borderLayer.BorderColor = view.BorderColor.ToCGColor ();
			borderLayer.BorderWidth = 1.0f;

			Control.Layer.AddSublayer (borderLayer);
			Control.BorderStyle = UITextBorderStyle.None;
		}
Ejemplo n.º 22
0
 public override void DrawLayer(CALayer layer, CGContext context)
 {
     context.SaveState ();
     context.SetFillColor (1.0f, 1.0f, 1.0f, 1.0f);
     context.FillRect (context.GetClipBoundingBox ());
     context.TranslateCTM (0.0f, layer.Bounds.Size.Height);
     context.ScaleCTM (1.0f, -1.0f);
     context.ConcatCTM (this.oParentController.currentPDFPage.GetDrawingTransform (CGPDFBox.Crop, layer.Bounds, 0, true));
     context.DrawPDFPage (this.oParentController.currentPDFPage);
     context.RestoreState ();
 }
		void Initialize ()
		{
			Console.WriteLine ("Creating Layer");
			
			// create our layer and set it's frame
			imgLayer = CreateLayerFromImage ();
			imgLayer.Frame = new RectangleF (200, 70, 114, 114);
			
			// add the layer to the layer tree so that it's visible
			View.Layer.AddSublayer (imgLayer);
		}
Ejemplo n.º 24
0
        public DrawingView()
        {
            BackgroundColor = UIColor.White;

            path = new CGPath ();

            layer = new CALayer ();
            layer.Bounds = new RectangleF (0, 0, 50, 50);
            layer.Position = new PointF (50, 50);
            layer.Contents = UIImage.FromFile ("monkey.png").CGImage;
            layer.ContentsGravity = CALayer.GravityResizeAspect;
        }
Ejemplo n.º 25
0
        public CircularProgressLayer(CALayer other)
            : base(other)
        {
            var otherProgressLayer = other as CircularProgressLayer;

            if (otherProgressLayer != null)
            {
                InnerColor = otherProgressLayer.InnerColor;
                InsideColor = otherProgressLayer.InsideColor;
                OuterColor = otherProgressLayer.OuterColor;
            }
        }
Ejemplo n.º 26
0
 static void RemoveSublayers(CALayer parent)
 {
     if (parent.Sublayers != null)
     {
         foreach (var layer in parent.Sublayers)
         {
             RemoveSublayers(layer);
             layer.RemoveFromSuperLayer();
             layer.Dispose();
         }
     }
 }
Ejemplo n.º 27
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad ();

            layer = new CALayer ();
            layer.Bounds = new CGRect (0, 0, 50, 50);
            layer.Position = new CGPoint (UIScreen.MainScreen.Bounds.Width / 2,     UIScreen.MainScreen.Bounds.Height / 2);
            layer.Contents = UIImage.FromFile ("sample.png").CGImage;
            layer.ContentsGravity = CALayer.GravityResizeAspectFill;

            View.Layer.AddSublayer (layer);
        }
Ejemplo n.º 28
0
		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();

			layer = new CALayer ();
			layer.Bounds = new CGRect (0, 0, 80, 80);
			layer.Position = new CGPoint (100, 100);
			layer.Contents = UIImage.FromFile("sample.png").CGImage;
			layer.ContentsGravity = CALayer.GravityResizeAspectFill;

			View.Layer.AddSublayer (layer);

		}
Ejemplo n.º 29
0
 private static CABasicAnimation FadeAnimation(CALayer layer, nfloat opacity, double duration)
 {
     CABasicAnimation animation = CABasicAnimation.FromKeyPath("opacity");
     if (layer.PresentationLayer != null)
     {
         animation.From = NSNumber.FromFloat(layer.Opacity);
     }
     animation.To = NSNumber.FromDouble(opacity);
     animation.FillMode = CAFillMode.Both;
     animation.RemovedOnCompletion = false;
     animation.Duration = duration;
     return animation;
 }
		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();

			layer = new CALayer ();
			layer.Bounds = new RectangleF (0, 0, 50, 50);
			layer.Position = new PointF (50, 50);
			layer.Contents = UIImage.FromFile ("monkey2.png").CGImage;
			layer.ContentsGravity = CALayer.GravityResize;
			layer.BorderWidth = 1.5f;
			layer.BorderColor = UIColor.Green.CGColor;

			View.Layer.AddSublayer (layer);
		}
Ejemplo n.º 31
0
        private void BeginSession()
        {
            try
            {
                NSError error       = null;
                var     deviceInput = new AVCaptureDeviceInput(captureDevice, out error);
                if (error == null && captureSession.CanAddInput(deviceInput))
                {
                    captureSession.AddInput(deviceInput);
                }
                previewLayer = new AVCaptureVideoPreviewLayer(captureSession)
                {
                    VideoGravity = AVLayerVideoGravity.ResizeAspect
                };
                //this.HomeView.BackgroundColor = UIColor.Black;
                previewLayer.Frame = this.HomeView.Layer.Bounds;

                this.HomeView.Layer.AddSublayer(previewLayer);

                captureDevice.LockForConfiguration(out error);
                if (error != null)
                {
                    Console.WriteLine(error);
                    captureDevice.UnlockForConfiguration();
                    return;
                }

                if (UIDevice.CurrentDevice.CheckSystemVersion(7, 0))
                {
                    captureDevice.ActiveVideoMinFrameDuration = new CMTime(1, 15);
                }
                captureDevice.UnlockForConfiguration();

                captureSession.StartRunning();

                // create a VideoDataOutput and add it to the sesion
                videoOut = new AVCaptureVideoDataOutput()
                {
                    AlwaysDiscardsLateVideoFrames = true,
                    WeakVideoSettings             = new CVPixelBufferAttributes()
                    {
                        PixelFormatType = CVPixelFormatType.CV32BGRA
                    }.Dictionary
                };

                if (captureSession.CanAddOutput(videoOut))
                {
                    captureSession.AddOutput(videoOut);
                }



                captureSession.CommitConfiguration();

                setupAVFoundationFaceDetection();

                //var OutputSampleDelegate = new VideoCapture(
                //(s) =>
                //{
                //    GreetingsLabel.Text = s;
                //    PopulateList(s);
                //}, new Action<CIImage, CGRect>(DrawFaces));

                //videoOut.SetSampleBufferDelegateQueue(OutputSampleDelegate, sessionQueue);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Ejemplo n.º 32
0
 public override void DrawLayer(CALayer layer, MonoTouch.CoreGraphics.CGContext context)
 {
     // implement your drawing
 }
Ejemplo n.º 33
0
        /// <summary>
        /// Creates a new <see cref="T:Xamarin.Interactive.Mac.MacInspectView"/> that represents the given layer.
        /// </summary>
        /// <param name="layerParent">The parent view of the layer.</param>
        /// <param name="layer">The layer itself.</param>
        /// <param name="visitedLayers">
        /// Layers we've already visited in building this tree. This method both checks sublayers against this
        /// collection and modifies it by adding sublayers it consumes.
        /// </param>
        /// <remarks>
        /// We need to keep track of this set of visited layers to avoid an oddity in the way that layers are
        /// presented in the AppKit "tree." Layers and views are actually two separate trees, with the layer
        /// tree being a child tree of the top-level window, and the individual layer properties of each
        /// UIView being pointers into various places in that tree.
        /// </remarks>
        public MacInspectView(NSView layerParent, CALayer layer, HashSet <IntPtr> visitedLayers)
        {
            if (layerParent == null)
            {
                throw new ArgumentNullException(nameof(layerParent));
            }
            if (layer == null)
            {
                throw new ArgumentNullException(nameof(layer));
            }

            this.layer = layer;
            this.view  = layerParent;

            SetHandle(ObjectCache.Shared.GetHandle(layer));
            PopulateTypeInformationFromObject(layer);

            Description = layer.Description;

            var superTransform = layer.SuperLayer?.GetChildTransform() ?? CATransform3D.Identity;

            // on iOS the layer transform has the view transform already applied
            // on macOs we have to composite it ourself if we are skipping the view
            // node in the inspector tree
            if (layerParent.Layer == layer && layer.SuperLayer == null)
            {
                if (layerParent.IsFlipped)
                {
                    superTransform = GetLocalTransform(layerParent);
                }
                else
                {
                    superTransform = GetLocalTransform(layerParent)
                                     .Translate(0, layer.Bounds.Height, 0)
                                     .Scale(1, -1, 1);
                }
            }

            if (!layer.Transform.IsIdentity || !superTransform.IsIdentity)
            {
                Transform = layer
                            .GetLocalTransform()
                            .Concat(superTransform)
                            .ToViewTransform();

                X      = layer.Bounds.X;
                Y      = layer.Bounds.Y;
                Width  = layer.Bounds.Width;
                Height = layer.Bounds.Height;
            }
            else
            {
                X      = layer.Frame.X;
                Y      = layer.Frame.Y;
                Width  = layer.Frame.Width;
                Height = layer.Frame.Height;
            }

            Kind = ViewKind.Secondary;
            // macOS doesn't have a concept of hidden but laid out, so it's either collapsed or visible.
            Visibility = layer.Hidden ? ViewVisibility.Collapsed : ViewVisibility.Visible;

            var sublayers = layer.Sublayers;

            if (sublayers?.Length > 0)
            {
                for (int i = 0; i < sublayers.Length; i++)
                {
                    var subLayer = sublayers [i];
                    if (!visitedLayers.Contains(subLayer.Handle))
                    {
                        base.AddSublayer(new MacInspectView(layerParent, subLayer, visitedLayers));
                        visitedLayers.Add(subLayer.Handle);
                    }
                }
            }
        }
Ejemplo n.º 34
0
        public override void DrawLayer(CALayer layer, CGContext context)
        {
            base.DrawLayer(layer, context);
            //set up drawing attributes



            var height = layer.Bounds.Height;
            var width  = layer.Bounds.Width;

            var radius = (float)((height / 2) * 0.8);
            var margin = ((width / Element.GetMaxRating) - (2 * radius)) / 2;
            //var margin = ((width - (Element.GetMaxRating * radius)) / 5);
            float space = (float)margin;
            var   y     = height / 2;

            //create geometry
            // Draw background circle
            CGPath pathRating  = new CGPath();
            CGPath pathUnRated = new CGPath();

            pathRating.AddArc(radius + space, y, radius, 0, 2.0f * (float)Math.PI, true);

            UIColor ratingColor = Element.RatingColor.ToUIColor();

            ratingColor.SetStroke();
            ratingColor.SetFill();

            //to test
            //int cnt;
            //for(cnt = 1; cnt <= Element.RateNumber; cnt++)
            //{
            //    CGPath pathRating1 = new CGPath();
            //    pathRating1.AddArc(radius + space, y, radius, 0, 2.0f * (float)Math.PI, true);
            //    space += radius * 2 + ((float)margin * 2);
            //    context.AddPath(pathRating);
            //    context.DrawPath(CGPathDrawingMode.Stroke);
            //}

            //UIColor.Gray.SetStroke();

            //for (; cnt <= Element.GetMaxRating; cnt++)
            //{
            //    CGPath pathUnRated1 = new CGPath();
            //    pathUnRated1.AddArc(radius + space, y, radius, 0, 2.0f * (float)Math.PI, true);
            //    space += radius * 2 + ((float)margin * 2);
            //    context.AddPath(pathUnRated1);
            //    context.DrawPath(CGPathDrawingMode.Stroke);
            //}

            for (int i = 1; i <= Element.GetMaxRating; i++)
            {
                if (i <= Element.RateNumber)
                {
                    pathRating.AddArc(radius + space, y, radius, 0, 2.0f * (float)Math.PI, true);
                }
                else
                {
                    UIColor.Gray.SetStroke();
                    pathUnRated.AddArc(radius + space, y, radius, 0, 2.0f * (float)Math.PI, true);
                }

                space += radius * 2 + ((float)margin * 2);
            }

            context.AddPath(pathRating);
            context.DrawPath(CGPathDrawingMode.Stroke);

            context.AddPath(pathUnRated);
            context.DrawPath(CGPathDrawingMode.Stroke);
        }
Ejemplo n.º 35
0
 public FormsNSImageView()
 {
     Layer      = new CALayer();
     WantsLayer = true;
 }
Ejemplo n.º 36
0
        public Ring(Layer layer, CALayer superLayer, double startPoint, double endPoint, double beatLength)
        {
            Layer       = layer;
            _superLayer = superLayer;

            // init the CALayers
            BackgroundLayer = new CALayer()
            {
                ContentsScale = NSScreen.MainScreen.BackingScaleFactor,
                //Frame = superLayer.Frame,
                Delegate = new BackgroundLayerDelegate(this)
            };

            TickMarksLayer = new CALayer()
            {
                ContentsScale = NSScreen.MainScreen.BackingScaleFactor,
                //Frame = superLayer.Frame,
                Delegate  = new TickLayerDelegate(this, beatLength, layer),
                ZPosition = 5
            };

            superLayer.AddSublayer(BackgroundLayer);
            superLayer.AddSublayer(TickMarksLayer);

            // find the tick rotations
            TickRotations = new LinkedList <nfloat>();

            if (!Layer.GetAllStreams().All(x => StreamInfoProvider.IsSilence(x.Info)))
            {
                nfloat frontOffset = 0;
                foreach (BeatCell bc in layer.Beat)
                {
                    if (StreamInfoProvider.IsSilence(bc.StreamInfo))
                    {
                        // add a silent value to the previous cell value
                        if (TickRotations.Last != null)
                        {
                            TickRotations.Last.Value += (nfloat)(bc.Bpm / beatLength * TWOPI);
                        }
                        else
                        {
                            frontOffset = (nfloat)(bc.Bpm / beatLength * TWOPI);
                        }
                    }
                    else
                    {
                        TickRotations.AddLast((nfloat)(bc.Bpm / beatLength * TWOPI));
                    }
                }

                if (frontOffset > 0)
                {
                    TickRotations.Last.Value += frontOffset;
                }
            }

            InnerRadiusLocation = (nfloat)startPoint * superLayer.Frame.Width;
            OuterRadiusLocation = (nfloat)endPoint * superLayer.Frame.Width;

            StartPoint = startPoint;
            EndPoint   = endPoint;

            //DrawStaticElements();

            // set the offset
            CurrentBpmInterval = Layer.OffsetBpm;
            while (StreamInfoProvider.IsSilence(Layer.Beat[BeatIndex].StreamInfo))
            {
                CurrentBpmInterval += Layer.Beat[BeatIndex++].Bpm;
                BeatIndex          %= Layer.Beat.Count;
            }

            // do some reseting when playback stops
            Metronome.Instance.Stopped += Instance_Stopped;
        }
Ejemplo n.º 37
0
        private void Animate(CALayer layer, float from, float to, float delayMilliseconds, float durationMilliseconds)
        {
            if (_isDiscrete)
            {
                var animation = CAKeyFrameAnimation.FromKeyPath(_property);
                animation.KeyTimes        = new NSNumber[] { new NSNumber(0.0), new NSNumber(1.0) };
                animation.Values          = new NSObject[] { _nsValueConversion(to) };
                animation.CalculationMode = CAKeyFrameAnimation.AnimationDescrete;
                _animation = animation;
            }
            else
            {
                var animation = CABasicAnimation.FromKeyPath(_property);
                animation.From           = _nsValueConversion(from);
                animation.To             = _nsValueConversion(to);
                animation.TimingFunction = _timingFunction;
                _animation = animation;
            }
            _animation.BeginTime           = CAAnimation.CurrentMediaTime() + delayMilliseconds / __millisecondsPerSecond;
            _animation.Duration            = durationMilliseconds / __millisecondsPerSecond;
            _animation.FillMode            = CAFillMode.Forwards;
            _animation.RemovedOnCompletion = false;

            if (this.Log().IsEnabled(Microsoft.Extensions.Logging.LogLevel.Debug))
            {
                this.Log().DebugFormat("CoreAnimation on property {0} from {1} to {2} is starting.", _property, from, to);
            }

            _onAnimationStarted = (s, e) =>
            {
                var anim = s as CAAnimation;

                if (anim == null)
                {
                    return;
                }

                if (this.Log().IsEnabled(Microsoft.Extensions.Logging.LogLevel.Debug))
                {
                    this.Log().DebugFormat("CoreAnimation on property {0} from {1} to {2} started.", _property, from, to);
                }

                anim.AnimationStarted -= _onAnimationStarted;
                anim.AnimationStopped += _onAnimationStopped;
            };

            _onAnimationStopped = (s, e) =>
            {
                var anim = s as CAAnimation;

                if (anim == null)
                {
                    return;
                }

                CATransaction.Begin();
                CATransaction.DisableActions = true;
                layer.SetValueForKeyPath(_nsValueConversion(to), new NSString(_property));
                CATransaction.Commit();

                anim.AnimationStopped -= _onAnimationStopped;

                if (e.Finished)
                {
                    if (this.Log().IsEnabled(Microsoft.Extensions.Logging.LogLevel.Debug))
                    {
                        this.Log().DebugFormat("CoreAnimation on property {0} from {1} to {2} finished.", _property, from, to);
                    }

                    _onFinish();

                    ExecuteIfLayer(l => l.RemoveAnimation(_key));
                }
                else
                {
                    if (this.Log().IsEnabled(Microsoft.Extensions.Logging.LogLevel.Debug))
                    {
                        this.Log().DebugFormat("CoreAnimation on property {0} from {1} to {2} stopped before finishing.", _property, from, to);
                    }

                    anim.AnimationStarted += _onAnimationStarted;
                }
            };

            _animation.AnimationStarted += _onAnimationStarted;

            layer.AddAnimation(_animation, _key);
        }
Ejemplo n.º 38
0
        public override async void ViewDidLoad()
        {
            base.ViewDidLoad();

            Console.WriteLine("N0rf3n - ViewDidLoad - Begin");

            try
            {
                Console.WriteLine("N0rf3n - ViewDidLoad - Begin/Try");

                var Verifica = new LAContext();                                                                     //Context
                var myReason = new NSString("Autenticación Biométrica");
                var autoriza = await Verifica.EvaluatePolicyAsync(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, //Await, es un proceso Asyncrono y toca cambiar el  public override void  por ->  public override async void y vamos a usar la validación biometrica.
                                                                  myReason);

                if (autoriza.Item1) //el primer elemento Item1 hace refenrecia al OK y el segundo al error.
                {
                    Console.WriteLine("N0rf3n - ViewDidLoad - Ingreso App - TouchID");

                    //Se establece todo el ancho y altura de la vista de la pantalla
                    Altura            = View.Bounds.Width;
                    Ancho             = View.Bounds.Height;
                    AnchoCapaa        = Altura / 2;
                    Altura            = Ancho / 6;
                    CapaImagen        = new CALayer(); //Se define una capa nueva.
                    CapaImagen.Bounds = new CGRect(Altura / 2 - Ancho,
                                                   Ancho / 2 - Altura / 2,
                                                   AnchoCapaa,
                                                   AlturaCapa);

                    CapaImagen.Position = new CGPoint(100, 100); //Se establece una posición.
                    CapaImagen.Contents = UIImage.FromFile("Tanjiro.jpg").CGImage;
                    View.Layer.AddSublayer(CapaImagen);          //Se agrega a la vista la nueva capa
                    var Actualiza = CapaImagen.Frame;            //se obtienen los frames de la capa imagen, para obtener las coordenadas
                    Movimiento = new CMMotionManager();          //instancia nueva del movimiento.


                    if (Movimiento.AccelerometerAvailable) //Validar si el dispositivo tiene el acelerometro esta disponible
                    {
                        //Si el aceleremetro esta disposnible le vamos a definir el intervalo para estar verificando los objectos que estan en el view controller

                        Movimiento.AccelerometerUpdateInterval = 0.02;
                        Movimiento.StartAccelerometerUpdates(NSOperationQueue.CurrentQueue, (data, error) =>//Metodo para detectar el movimiento del dispositivo.
                        {
                            //Se capturan las coordenadas de la capa imagen
                            ActualizaX = CapaImagen.Frame.X;
                            ActualizaY = CapaImagen.Frame.Y;

                            if (ActualizaX + (nfloat)data.Acceleration.X * 10 > 0 &&                 //Si el acelerometro se mueve
                                ActualizaX + (nfloat)data.Acceleration.X * 10 < Altura - AnchoCapaa) //para que el objecto se mantega en la vista actual.
                            {
                                //Se actualiza la posicion.
                                Actualiza.X = ActualizaX + (nfloat)data.Acceleration.X * 10; // el objeto empieza a tener movimiento
                            }

                            if (ActualizaY + (nfloat)data.Acceleration.Y * 10 > 0 &&                //Si el acelerometro se mueve
                                ActualizaY + (nfloat)data.Acceleration.Y * 10 < Ancho - AlturaCapa) //para que el objecto se mantega en la vista actual.
                            {
                                //Se actualiza la posicion.
                                Actualiza.Y = ActualizaY + (nfloat)data.Acceleration.Y * 10; // el objeto empieza a tener movimiento

                                lblValueX.Text = data.Acceleration.X.ToString("00");
                                lblValueY.Text = data.Acceleration.Y.ToString("00");
                                lblValueZ.Text = data.Acceleration.Z.ToString("00");

                                //Se realiza la actualizaciòn de la capa imagen
                                CapaImagen.Frame = Actualiza; //la variable tiene los valores en X y Z
                            }
                        }
                                                             );
                    }
                }
                else
                {
                    // System.Threading.Thread.CurrentThread.Abort();//Salga de la venta,  la coloque en segundo plano y coloque la App en primer plano
                    Console.WriteLine("N0rf3n - ViewDidLoad - Else");
                    Thread.CurrentThread.Abort();
                }

                Console.WriteLine("N0rf3n - ViewDidLoad - End");
            }
            catch (Exception ex)
            {
                Console.WriteLine("N0rf3n - ViewDidLoad - End/Catch Error : " + ex.Message);

                var alerta = UIAlertController.Create("Estado",
                                                      ex.Message,
                                                      UIAlertControllerStyle.Alert);


                alerta.AddAction(UIAlertAction.Create("Aceptar", UIAlertActionStyle.Default, null));

                PresentViewController(alerta, true, null);
            }
        }
Ejemplo n.º 39
0
        CALayer LayerForPoint(CGPoint location)
        {
            CALayer layer = Layer.PresentationLayer.HitTest(location);

            return(layer != null ? layer.ModelLayer : null);
        }
Ejemplo n.º 40
0
 public StatusIcon(StatusBar bar, CALayer layer, NSTrackingArea trackingArea)
 {
     this.bar     = bar;
     this.layer   = layer;
     TrackingArea = trackingArea;
 }
Ejemplo n.º 41
0
        private static IDisposable InnerCreateLayer(UIElement owner, CALayer parent, LayoutState state)
        {
            var area            = state.Area;
            var background      = state.Background;
            var borderThickness = state.BorderThickness;
            var borderBrush     = state.BorderBrush;
            var cornerRadius    = state.CornerRadius;

            var disposables = new CompositeDisposable();
            var sublayers   = new List <CALayer>();

            var adjustedLineWidth       = borderThickness.Top;
            var adjustedLineWidthOffset = adjustedLineWidth / 2;

            var adjustedArea = area;

            adjustedArea = adjustedArea.Shrink((nfloat)adjustedLineWidthOffset);

            if (cornerRadius != CornerRadius.None)
            {
                var maxRadius = Math.Max(0, Math.Min((float)area.Width / 2 - adjustedLineWidthOffset, (float)area.Height / 2 - adjustedLineWidthOffset));
                cornerRadius = new CornerRadius(
                    Math.Min(cornerRadius.TopLeft, maxRadius),
                    Math.Min(cornerRadius.TopRight, maxRadius),
                    Math.Min(cornerRadius.BottomRight, maxRadius),
                    Math.Min(cornerRadius.BottomLeft, maxRadius));

                CAShapeLayer layer = new CAShapeLayer();
                layer.LineWidth = (nfloat)adjustedLineWidth;
                layer.FillColor = null;


                Brush.AssignAndObserveBrush(borderBrush, color => layer.StrokeColor = color)
                .DisposeWith(disposables);
                var path = GetRoundedPath(cornerRadius, adjustedArea);

                var outerPath = GetRoundedPath(cornerRadius, area);

                var insertionIndex = 0;

                if (background is GradientBrush gradientBackground)
                {
                    var fillMask = new CAShapeLayer()
                    {
                        Path  = path,
                        Frame = area,
                        // We only use the fill color to create the mask area
                        FillColor = _Color.White.CGColor,
                    };
                    // We reduce the adjustedArea again so that the gradient is inside the border (like in Windows)
                    adjustedArea = adjustedArea.Shrink((nfloat)adjustedLineWidthOffset);

                    CreateGradientBrushLayers(area, adjustedArea, parent, sublayers, ref insertionIndex, gradientBackground, fillMask);
                }
                else if (background is SolidColorBrush scbBackground)
                {
                    Brush.AssignAndObserveBrush(scbBackground, color => layer.FillColor = color)
                    .DisposeWith(disposables);
                }
                else if (background is ImageBrush imgBackground)
                {
                    var uiImage = imgBackground.ImageSource?.ImageData;
                    if (uiImage != null && uiImage.Size != CGSize.Empty)
                    {
                        var fillMask = new CAShapeLayer()
                        {
                            Path  = path,
                            Frame = area,
                            // We only use the fill color to create the mask area
                            FillColor = _Color.White.CGColor,
                        };
                        // We reduce the adjustedArea again so that the image is inside the border (like in Windows)
                        adjustedArea = adjustedArea.Shrink((nfloat)adjustedLineWidthOffset);

                        CreateImageBrushLayers(area, adjustedArea, parent, sublayers, ref insertionIndex, imgBackground, fillMask);
                    }
                }
                else
                {
                    layer.FillColor = Colors.Transparent;
                }

                layer.Path = path;

                sublayers.Add(layer);
                parent.InsertSublayer(layer, insertionIndex);

                parent.Mask = new CAShapeLayer()
                {
                    Path  = outerPath,
                    Frame = area,
                    // We only use the fill color to create the mask area
                    FillColor = _Color.White.CGColor,
                };

                if (owner != null)
                {
                    owner.ClippingIsSetByCornerRadius = true;
                }

                state.BoundsPath = path;
            }
            else
            {
                if (background is GradientBrush gradientBackground)
                {
                    var fullArea = new CGRect(
                        area.X + borderThickness.Left,
                        area.Y + borderThickness.Top,
                        area.Width - borderThickness.Left - borderThickness.Right,
                        area.Height - borderThickness.Top - borderThickness.Bottom);

                    var insideArea     = new CGRect(CGPoint.Empty, fullArea.Size);
                    var insertionIndex = 0;

                    CreateGradientBrushLayers(fullArea, insideArea, parent, sublayers, ref insertionIndex, gradientBackground, fillMask: null);
                }
                else if (background is SolidColorBrush scbBackground)
                {
                    Brush.AssignAndObserveBrush(scbBackground, c => parent.BackgroundColor = c)
                    .DisposeWith(disposables);

                    // This is required because changing the CornerRadius changes the background drawing
                    // implementation and we don't want a rectangular background behind a rounded background.
                    Disposable.Create(() => parent.BackgroundColor = null)
                    .DisposeWith(disposables);
                }
                else if (background is ImageBrush imgBackground)
                {
                    var uiImage = imgBackground.ImageSource?.ImageData;
                    if (uiImage != null && uiImage.Size != CGSize.Empty)
                    {
                        var fullArea = new CGRect(
                            area.X + borderThickness.Left,
                            area.Y + borderThickness.Top,
                            area.Width - borderThickness.Left - borderThickness.Right,
                            area.Height - borderThickness.Top - borderThickness.Bottom);

                        var insideArea     = new CGRect(CGPoint.Empty, fullArea.Size);
                        var insertionIndex = 0;

                        CreateImageBrushLayers(fullArea, insideArea, parent, sublayers, ref insertionIndex, imgBackground, fillMask: null);
                    }
                }
                else
                {
                    parent.BackgroundColor = Colors.Transparent;
                }

                if (borderThickness != Thickness.Empty)
                {
                    Action <Action <CAShapeLayer, CGPath> > createLayer = builder =>
                    {
                        CAShapeLayer layer = new CAShapeLayer();
                        var          path  = new CGPath();

                        Brush.AssignAndObserveBrush(borderBrush, c => layer.StrokeColor = c)
                        .DisposeWith(disposables);

                        builder(layer, path);
                        layer.Path = path;

                        // Must be inserted below the other subviews, which may happen when
                        // the current view has subviews.
                        sublayers.Add(layer);
                        parent.InsertSublayer(layer, 0);
                    };

                    if (borderThickness.Top != 0)
                    {
                        createLayer((l, path) =>
                        {
                            l.LineWidth         = (nfloat)borderThickness.Top;
                            var lineWidthAdjust = (nfloat)(borderThickness.Top / 2);
                            path.MoveToPoint(area.X + (nfloat)borderThickness.Left, area.Y + lineWidthAdjust);
                            path.AddLineToPoint(area.X + area.Width - (nfloat)borderThickness.Right, area.Y + lineWidthAdjust);
                            path.CloseSubpath();
                        });
                    }

                    if (borderThickness.Bottom != 0)
                    {
                        createLayer((l, path) =>
                        {
                            l.LineWidth         = (nfloat)borderThickness.Bottom;
                            var lineWidthAdjust = borderThickness.Bottom / 2;
                            path.MoveToPoint(area.X + (nfloat)borderThickness.Left, (nfloat)(area.Y + area.Height - lineWidthAdjust));
                            path.AddLineToPoint(area.X + area.Width - (nfloat)borderThickness.Right, (nfloat)(area.Y + area.Height - lineWidthAdjust));
                            path.CloseSubpath();
                        });
                    }

                    if (borderThickness.Left != 0)
                    {
                        createLayer((l, path) =>
                        {
                            l.LineWidth         = (nfloat)borderThickness.Left;
                            var lineWidthAdjust = borderThickness.Left / 2;
                            path.MoveToPoint((nfloat)(area.X + lineWidthAdjust), area.Y);
                            path.AddLineToPoint((nfloat)(area.X + lineWidthAdjust), area.Y + area.Height);
                            path.CloseSubpath();
                        });
                    }

                    if (borderThickness.Right != 0)
                    {
                        createLayer((l, path) =>
                        {
                            l.LineWidth         = (nfloat)borderThickness.Right;
                            var lineWidthAdjust = borderThickness.Right / 2;
                            path.MoveToPoint((nfloat)(area.X + area.Width - lineWidthAdjust), area.Y);
                            path.AddLineToPoint((nfloat)(area.X + area.Width - lineWidthAdjust), area.Y + area.Height);
                            path.CloseSubpath();
                        });
                    }
                }

                state.BoundsPath = CGPath.FromRect(parent.Bounds);
            }

            disposables.Add(() =>
            {
                foreach (var sl in sublayers)
                {
                    sl.RemoveFromSuperLayer();
                    sl.Dispose();
                }

                if (owner != null)
                {
                    owner.ClippingIsSetByCornerRadius = false;
                }
            }
                            );
            return(disposables);
        }
Ejemplo n.º 42
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            //CGColor[] colors = new CGColor[] { UIColor.FromRGB(98,107,186).CGColor,
            //    UIColor.FromRGB(57,122,193).CGColor};
            //gradientLayer = new CAGradientLayer();
            //gradientLayer.Frame = this.View.Bounds;
            //gradientLayer.Colors = colors;
            //this.View.Layer.InsertSublayer(gradientLayer, 0);

            gradientLayer        = new CAGradientLayer();
            gradientLayer.Colors = new[] { UIColor.FromRGB(98, 107, 186).CGColor, UIColor.FromRGB(57, 122, 193).CGColor };
            gradientLayer.Frame  = this.View.Bounds;
            View.Layer.InsertSublayer(gradientLayer, 0);


            //Set Placeholder Text Color
            txtUserName.AttributedPlaceholder     = new NSAttributedString("Username", null, UIColor.White);
            txtEmail.AttributedPlaceholder        = new NSAttributedString("Emial", null, UIColor.White);
            txtMobileNumber.AttributedPlaceholder = new NSAttributedString("Mobile number", null, UIColor.White);
            txtPassword.AttributedPlaceholder     = new NSAttributedString("Password", null, UIColor.White);

            //Show Clear Button While Editing Values
            txtUserName.ClearButtonMode     = UITextFieldViewMode.WhileEditing;
            txtEmail.ClearButtonMode        = UITextFieldViewMode.WhileEditing;
            txtMobileNumber.ClearButtonMode = UITextFieldViewMode.WhileEditing;
            txtPassword.ClearButtonMode     = UITextFieldViewMode.WhileEditing;

            txtPassword.SecureTextEntry = true;

            borderUserName.Layer.BorderWidth = 2;
            borderUserName.Layer.BorderColor = UIColor.White.CGColor;

            borderEmail.Layer.BorderWidth = 2;
            borderEmail.Layer.BorderColor = UIColor.White.CGColor;

            borderMobileNumber.Layer.BorderWidth = 2;
            borderMobileNumber.Layer.BorderColor = UIColor.White.CGColor;

            borderPassword.Layer.BorderWidth = 2;
            borderPassword.Layer.BorderColor = UIColor.White.CGColor;

            borderDDL.Layer.BorderWidth = 2;
            borderDDL.Layer.BorderColor = UIColor.White.CGColor;

            //UIPickerView Values

            var list = new List <string>
            {
                "Are you", "Provider", "Consumer"
            };

            var picker = new UserTypeViewModel(list);

            rolePicker.Model = picker;
            rolePicker.ShowSelectionIndicator = true;
            //picker.ValueChanged+=(sender, e) =>
            //{
            //    var val = picker.SelectedValue;
            //};

            //Pickerview Custom Appearance
            var layer = new CALayer();

            layer.Frame           = new CGRect(15, 15, rolePicker.Frame.Width - 30, rolePicker.Frame.Height - 30);
            layer.CornerRadius    = 10;
            layer.BackgroundColor = UIColor.White.CGColor;
            rolePicker.Layer.Mask = layer;


            //Validations
            //txtUserName.EditingDidEnd += (sender, e) =>
            //{
            //    if(((UITextField)sender).Text.Length <= 0)
            //    {
            //        InvokeOnMainThread(()=>
            //        {
            //            borderUserName.Layer.BorderColor = UIColor.Red.CGColor;
            //            txtUserName.AttributedPlaceholder = new NSAttributedString("Username is required", null, UIColor.Yellow);
            //        });
            //    }
            //    else
            //    {
            //        borderUserName.Layer.BorderColor = UIColor.Green.CGColor;
            //    }
            //};

            //txtEmail.EditingDidEnd += (sender, e) =>
            //{
            //    if(((UITextField)sender).Text.Length > 0)
            //    {
            //        if(!Regex.Match(txtEmail.Text, @"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$").Success)
            //        {
            //            borderEmail.Layer.BorderColor = UIColor.Red.CGColor;
            //            txtEmail.AttributedPlaceholder = new NSAttributedString("Please enter valid email id", null, UIColor.Yellow);
            //        }
            //        else
            //        {
            //            borderEmail.Layer.BorderColor = UIColor.Green.CGColor;
            //            txtEmail.Placeholder = "";
            //        }
            //    }
            //};


            btnBack.TouchUpInside += (sender, e) =>
            {
                this.NavigationController.PopViewController(true);
            };

            btnSignUp.TouchUpInside += (sender, e) =>
            {
                var apiCall = new ServiceApi().Register(txtUserName.Text, txtEmail.Text, txtMobileNumber.Text, txtPassword.Text, picker.SelectedValue, lat, lng);
                apiCall.HandleError(null, true);

                apiCall.OnSucess((result) =>
                {
                    var okAlertController = UIAlertController.Create("Alert", "Registration successfull", UIAlertControllerStyle.Alert);
                    okAlertController.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Destructive, null));
                    PresentViewController(okAlertController, true, null);
                });
            };
        }
Ejemplo n.º 43
0
        private static IDisposable InnerCreateLayer(CALayer parent, CGRect area, Brush background, Thickness borderThickness, Brush borderBrush, CornerRadius cornerRadius)
        {
            var disposables = new CompositeDisposable();
            var sublayers   = new List <CALayer>();

            var adjustedLineWidth       = borderThickness.Top;
            var adjustedLineWidthOffset = adjustedLineWidth / 2;

            var adjustedArea = area;

            adjustedArea = adjustedArea.Shrink((nfloat)adjustedLineWidthOffset);

            if (cornerRadius != CornerRadius.None)
            {
                var maxRadius = Math.Max(0, Math.Min((float)area.Width / 2 - adjustedLineWidthOffset, (float)area.Height / 2 - adjustedLineWidthOffset));
                cornerRadius = new CornerRadius(
                    Math.Min(cornerRadius.TopLeft, maxRadius),
                    Math.Min(cornerRadius.TopRight, maxRadius),
                    Math.Min(cornerRadius.BottomRight, maxRadius),
                    Math.Min(cornerRadius.BottomLeft, maxRadius));

                CAShapeLayer layer = new CAShapeLayer();
                layer.LineWidth = (nfloat)adjustedLineWidth;
                layer.FillColor = null;

                var path = new CGPath();

                Brush.AssignAndObserveBrush(borderBrush, color => layer.StrokeColor = color)
                .DisposeWith(disposables);

                // How AddArcToPoint works:
                // http://www.twistedape.me.uk/blog/2013/09/23/what-arctopointdoes/

                path.MoveToPoint(adjustedArea.GetMidX(), adjustedArea.Y);
                path.AddArcToPoint(adjustedArea.Right, adjustedArea.Top, adjustedArea.Right, adjustedArea.GetMidY(), (float)cornerRadius.TopRight);
                path.AddArcToPoint(adjustedArea.Right, adjustedArea.Bottom, adjustedArea.GetMidX(), adjustedArea.Bottom, (float)cornerRadius.BottomRight);
                path.AddArcToPoint(adjustedArea.Left, adjustedArea.Bottom, adjustedArea.Left, adjustedArea.GetMidY(), (float)cornerRadius.BottomLeft);
                path.AddArcToPoint(adjustedArea.Left, adjustedArea.Top, adjustedArea.GetMidX(), adjustedArea.Top, (float)cornerRadius.TopLeft);

                path.CloseSubpath();

                var lgbBackground  = background as LinearGradientBrush;
                var scbBackground  = background as SolidColorBrush;
                var imgBackground  = background as ImageBrush;
                var insertionIndex = 0;

                if (lgbBackground != null)
                {
                    var fillMask = new CAShapeLayer()
                    {
                        Path  = path,
                        Frame = area,
                        // We only use the fill color to create the mask area
                        FillColor = UIColor.White.CGColor,
                    };

                    // We reduce the adjustedArea again so that the gradient is inside the border (like in Windows)
                    adjustedArea = adjustedArea.Shrink((nfloat)adjustedLineWidthOffset);

                    CreateLinearGradientBrushLayers(area, adjustedArea, parent, sublayers, ref insertionIndex, lgbBackground, fillMask);
                }
                else if (scbBackground != null)
                {
                    Brush.AssignAndObserveBrush(scbBackground, color => layer.FillColor = color)
                    .DisposeWith(disposables);
                }
                else if (imgBackground != null)
                {
                    var uiImage = imgBackground.ImageSource?.ImageData;
                    if (uiImage != null && uiImage.Size != CGSize.Empty)
                    {
                        var fillMask = new CAShapeLayer()
                        {
                            Path  = path,
                            Frame = area,
                            // We only use the fill color to create the mask area
                            FillColor = UIColor.White.CGColor,
                        };

                        // We reduce the adjustedArea again so that the image is inside the border (like in Windows)
                        adjustedArea = adjustedArea.Shrink((nfloat)adjustedLineWidthOffset);

                        CreateImageBrushLayers(area, adjustedArea, parent, sublayers, ref insertionIndex, imgBackground, fillMask);
                    }
                }
                else
                {
                    layer.FillColor = Colors.Transparent;
                }

                layer.Path = path;

                sublayers.Add(layer);
                parent.InsertSublayer(layer, insertionIndex);
            }
            else
            {
                var lgbBackground = background as LinearGradientBrush;
                var scbBackground = background as SolidColorBrush;
                var imgBackground = background as ImageBrush;

                if (lgbBackground != null)
                {
                    var fullArea = new CGRect(
                        area.X + borderThickness.Left,
                        area.Y + borderThickness.Top,
                        area.Width - borderThickness.Left - borderThickness.Right,
                        area.Height - borderThickness.Top - borderThickness.Bottom);

                    var insideArea     = new CGRect(CGPoint.Empty, fullArea.Size);
                    var insertionIndex = 0;

                    CreateLinearGradientBrushLayers(fullArea, insideArea, parent, sublayers, ref insertionIndex, lgbBackground, fillMask: null);
                }
                else if (scbBackground != null)
                {
                    Brush.AssignAndObserveBrush(scbBackground, c => parent.BackgroundColor = c)
                    .DisposeWith(disposables);

                    // This is required because changing the CornerRadius changes the background drawing
                    // implementation and we don't want a rectangular background behind a rounded background.
                    Disposable.Create(() => parent.BackgroundColor = null)
                    .DisposeWith(disposables);
                }
                else if (imgBackground != null)
                {
                    var uiImage = imgBackground.ImageSource?.ImageData;
                    if (uiImage != null && uiImage.Size != CGSize.Empty)
                    {
                        var fullArea = new CGRect(
                            area.X + borderThickness.Left,
                            area.Y + borderThickness.Top,
                            area.Width - borderThickness.Left - borderThickness.Right,
                            area.Height - borderThickness.Top - borderThickness.Bottom);

                        var insideArea     = new CGRect(CGPoint.Empty, fullArea.Size);
                        var insertionIndex = 0;

                        CreateImageBrushLayers(fullArea, insideArea, parent, sublayers, ref insertionIndex, imgBackground, fillMask: null);
                    }
                }
                else
                {
                    parent.BackgroundColor = Colors.Transparent;
                }

                if (borderThickness != Thickness.Empty)
                {
                    var strokeColor = borderBrush ?? SolidColorBrushHelper.Transparent;

                    Action <Action <CAShapeLayer, CGPath> > createLayer = builder =>
                    {
                        CAShapeLayer layer = new CAShapeLayer();
                        var          path  = new CGPath();

                        Brush.AssignAndObserveBrush(borderBrush, c => layer.StrokeColor = c)
                        .DisposeWith(disposables);

                        builder(layer, path);
                        layer.Path = path;

                        // Must be inserted below the other subviews, which may happen when
                        // the current view has subviews.
                        sublayers.Add(layer);
                        parent.InsertSublayer(layer, 0);
                    };

                    if (borderThickness.Top != 0)
                    {
                        createLayer((l, path) =>
                        {
                            l.LineWidth         = (nfloat)borderThickness.Top;
                            var lineWidthAdjust = (nfloat)(borderThickness.Top / 2);
                            path.MoveToPoint(area.X, area.Y + lineWidthAdjust);
                            path.AddLineToPoint(area.X + area.Width, area.Y + lineWidthAdjust);
                            path.CloseSubpath();
                        });
                    }

                    if (borderThickness.Bottom != 0)
                    {
                        createLayer((l, path) =>
                        {
                            l.LineWidth         = (nfloat)borderThickness.Bottom;
                            var lineWidthAdjust = borderThickness.Bottom / 2;
                            path.MoveToPoint(area.X, (nfloat)(area.Y + area.Height - lineWidthAdjust));
                            path.AddLineToPoint(area.X + area.Width, (nfloat)(area.Y + area.Height - lineWidthAdjust));
                            path.CloseSubpath();
                        });
                    }

                    if (borderThickness.Left != 0)
                    {
                        createLayer((l, path) =>
                        {
                            l.LineWidth         = (nfloat)borderThickness.Left;
                            var lineWidthAdjust = borderThickness.Left / 2;
                            path.MoveToPoint((nfloat)(area.X + lineWidthAdjust), area.Y);
                            path.AddLineToPoint((nfloat)(area.X + lineWidthAdjust), area.Y + area.Height);
                            path.CloseSubpath();
                        });
                    }

                    if (borderThickness.Right != 0)
                    {
                        createLayer((l, path) =>
                        {
                            l.LineWidth         = (nfloat)borderThickness.Right;
                            var lineWidthAdjust = borderThickness.Right / 2;
                            path.MoveToPoint((nfloat)(area.X + area.Width - lineWidthAdjust), area.Y);
                            path.AddLineToPoint((nfloat)(area.X + area.Width - lineWidthAdjust), area.Y + area.Height);
                            path.CloseSubpath();
                        });
                    }
                }
            }

            disposables.Add(() =>
            {
                foreach (var sl in sublayers)
                {
                    sl.RemoveFromSuperLayer();
                    sl.Dispose();
                }
            }
                            );
            return(disposables);
        }
        private static IDisposable InnerCreateLayer(UIElement owner, CALayer parent, LayoutState state)
        {
            var area             = state.Area;
            var background       = state.Background;
            var borderThickness  = state.BorderThickness;
            var borderBrush      = state.BorderBrush;
            var cornerRadius     = state.CornerRadius;
            var backgroundSizing = state.BackgroundSizing;

            var disposables = new CompositeDisposable();
            var sublayers   = new List <CALayer>();

            var heightOffset = ((float)borderThickness.Top / 2) + ((float)borderThickness.Bottom / 2);
            var widthOffset  = ((float)borderThickness.Left / 2) + ((float)borderThickness.Right / 2);
            var halfWidth    = (float)area.Width / 2;
            var halfHeight   = (float)area.Height / 2;
            var adjustedArea = area;

            adjustedArea = adjustedArea.Shrink(
                (nfloat)borderThickness.Left,
                (nfloat)borderThickness.Top,
                (nfloat)borderThickness.Right,
                (nfloat)borderThickness.Bottom
                );

            if (cornerRadius != CornerRadius.None)
            {
                var maxOuterRadius = Math.Max(0, Math.Min(halfWidth - widthOffset, halfHeight - heightOffset));
                var maxInnerRadius = Math.Max(0, Math.Min(halfWidth, halfHeight));

                cornerRadius = new CornerRadius(
                    Math.Min(cornerRadius.TopLeft, maxOuterRadius),
                    Math.Min(cornerRadius.TopRight, maxOuterRadius),
                    Math.Min(cornerRadius.BottomRight, maxOuterRadius),
                    Math.Min(cornerRadius.BottomLeft, maxOuterRadius));

                var innerCornerRadius = new CornerRadius(
                    Math.Min(cornerRadius.TopLeft, maxInnerRadius),
                    Math.Min(cornerRadius.TopRight, maxInnerRadius),
                    Math.Min(cornerRadius.BottomRight, maxInnerRadius),
                    Math.Min(cornerRadius.BottomLeft, maxInnerRadius));

                var outerLayer      = new CAShapeLayer();
                var backgroundLayer = new CAShapeLayer();
                backgroundLayer.FillColor = null;
                outerLayer.FillRule       = CAShapeLayer.FillRuleEvenOdd;
                outerLayer.LineWidth      = 0;


                var path      = GetRoundedRect(cornerRadius, innerCornerRadius, area, adjustedArea);
                var innerPath = GetRoundedPath(cornerRadius, adjustedArea);
                var outerPath = GetRoundedPath(cornerRadius, area);

                var isInnerBorderEdge = backgroundSizing == BackgroundSizing.InnerBorderEdge;
                var backgroundPath    = isInnerBorderEdge ? innerPath : outerPath;
                var backgroundArea    = isInnerBorderEdge ? adjustedArea : area;

                var insertionIndex = 0;

                if (background is GradientBrush gradientBackground)
                {
                    var fillMask = new CAShapeLayer()
                    {
                        Path  = backgroundPath,
                        Frame = area,
                        // We only use the fill color to create the mask area
                        FillColor = _Color.White.CGColor,
                    };

                    CreateGradientBrushLayers(area, backgroundArea, parent, sublayers, ref insertionIndex, gradientBackground, fillMask);
                }
                else if (background is SolidColorBrush scbBackground)
                {
                    Brush.AssignAndObserveBrush(scbBackground, color => backgroundLayer.FillColor = color)
                    .DisposeWith(disposables);
                }
                else if (background is ImageBrush imgBackground)
                {
                    var imgSrc = imgBackground.ImageSource;
                    if (imgSrc != null && imgSrc.TryOpenSync(out var uiImage) && uiImage.Size != CGSize.Empty)
                    {
                        var fillMask = new CAShapeLayer()
                        {
                            Path  = backgroundPath,
                            Frame = area,
                            // We only use the fill color to create the mask area
                            FillColor = _Color.White.CGColor,
                        };

                        CreateImageBrushLayers(area, backgroundArea, parent, sublayers, ref insertionIndex, imgBackground, fillMask);
                    }
                }
                else if (background is AcrylicBrush acrylicBrush)
                {
                    var fillMask = new CAShapeLayer()
                    {
                        Path  = backgroundPath,
                        Frame = area,
                        // We only use the fill color to create the mask area
                        FillColor = _Color.White.CGColor,
                    };

                    acrylicBrush.Subscribe(owner, area, backgroundArea, parent, sublayers, ref insertionIndex, fillMask)
                    .DisposeWith(disposables);
                }
                else if (background is XamlCompositionBrushBase unsupportedCompositionBrush)
                {
                    Brush.AssignAndObserveBrush(unsupportedCompositionBrush, color => backgroundLayer.FillColor = color)
                    .DisposeWith(disposables);
                }
                else
                {
                    backgroundLayer.FillColor = Colors.Transparent;
                }

                if (borderBrush is SolidColorBrush scbBorder || borderBrush == null)
                {
                    Brush.AssignAndObserveBrush(borderBrush, color =>
                    {
                        outerLayer.StrokeColor = color;
                        outerLayer.FillColor   = color;
                    })
                    .DisposeWith(disposables);
                }
                else if (borderBrush is GradientBrush gradientBorder)
                {
                    var fillMask = new CAShapeLayer()
                    {
                        Path  = path,
                        Frame = area,
                        // We only use the fill color to create the mask area
                        FillColor = _Color.White.CGColor,
                    };

                    var borderLayerIndex = parent.Sublayers.Length;
                    CreateGradientBrushLayers(area, area, parent, sublayers, ref borderLayerIndex, gradientBorder, fillMask);
                }


                outerLayer.Path      = path;
                backgroundLayer.Path = backgroundPath;

                sublayers.Add(outerLayer);
                sublayers.Add(backgroundLayer);
                parent.AddSublayer(outerLayer);
                parent.InsertSublayer(backgroundLayer, insertionIndex);


                parent.Mask = new CAShapeLayer()
                {
                    Path  = outerPath,
                    Frame = area,
                    // We only use the fill color to create the mask area
                    FillColor = _Color.White.CGColor,
                };

                if (owner != null)
                {
                    owner.ClippingIsSetByCornerRadius = true;
                }

                state.BoundsPath = outerPath;
            }
Ejemplo n.º 45
0
            public void DrawLayer(CALayer layer, CGContext context)
            {
                context.SaveState();

                context.SetLineWidth(2);

                // draw each tickmark
                int center = (int)(layer.Frame.Width / 2);

                context.TranslateCTM(center, center);

                nfloat initialRotation = (nfloat)((Layer.OffsetBpm + Layer.Beat.TakeWhile(x => StreamInfoProvider.IsSilence(x.StreamInfo)).Select(x => x.Bpm).Sum()) / BeatLength * -TWOPI);

                context.RotateCTM(initialRotation);

                double total = 0;
                int    start = (int)(Ring.InnerRadiusLocation);
                int    end   = (int)(Ring.OuterRadiusLocation);

                if (Ring.TickRotations.Any())
                {
                    var rotation = Ring.TickRotations.First;
                    while (total < TWOPI)
                    {
                        if (rotation == null)
                        {
                            rotation = Ring.TickRotations.First;
                        }

                        context.MoveTo(0, start);
                        context.AddLineToPoint(0, end);


                        context.RotateCTM(-rotation.Value);

                        total += rotation.Value;

                        rotation = rotation.Next;
                    }

                    context.ReplacePathWithStrokedPath();
                }

                context.Clip();

                // clipped gradient
                var gradient = new CGGradient(
                    CGColorSpace.CreateDeviceRGB(),
                    new CGColor[] { NSColor.Gray.CGColor, NSColor.White.CGColor }
                    );

                context.DrawRadialGradient(
                    gradient,
                    new CGPoint(0, 0),
                    Ring.InnerRadiusLocation,
                    new CGPoint(0, 0),
                    Ring.OuterRadiusLocation,
                    CGGradientDrawingOptions.None
                    );

                context.RestoreState();
            }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            var gradientLayer = new CAGradientLayer();

            gradientLayer.Colors    = new[] { UIColor.FromRGB(98, 107, 186).CGColor, UIColor.FromRGB(57, 122, 193).CGColor };
            gradientLayer.Locations = new NSNumber[] { 0, 1 };
            gradientLayer.Frame     = new CGRect(0, 0, HeaderView.Frame.Width + 50, HeaderView.Frame.Height);
            HeaderView.Layer.InsertSublayer(gradientLayer, 0);

            //var buttonGradientLayer = new CAGradientLayer();
            //buttonGradientLayer.Colors = new[] { UIColor.FromRGB(98, 107, 186).CGColor, UIColor.FromRGB(57, 122, 193).CGColor };
            //buttonGradientLayer.Frame = btnSendMessage.Layer.Bounds;
            //buttonGradientLayer.CornerRadius = btnSendMessage.Layer.CornerRadius;
            //buttonGradientLayer.Locations = new NSNumber[] { 0, 1 };
            //btnSendMessage.Layer.AddSublayer(buttonGradientLayer);

            btnSendMessage.BackgroundColor = UIColor.FromRGB(98, 107, 186);

            CALayer profileImageCircle = ProfilePicture.Layer;

            profileImageCircle.CornerRadius  = 25;
            profileImageCircle.BorderColor   = UIColor.White.CGColor;
            profileImageCircle.BorderWidth   = 1.5f;
            profileImageCircle.MasksToBounds = true;

            //Circular Revel View
            //RevelView.Layer.BorderColor = UIColor.LightGray.CGColor;
            //RevelView.Layer.BorderWidth = 1;
            RevelView.Layer.CornerRadius = 5;

            var count = 1;

            btnAttachement.TouchUpInside += (sender, e) =>
            {
                if (count == 1)
                {
                    //SlideHorizontaly(RevelView, true, true, 2, null);
                    //SlideVerticaly(RevelView, true, true, 1, null);
                    //FadeAnimation(RevelView, true, 1, null);
                    Zoom(RevelView, true, 0.7, null);
                    //Rotate(RevelView, true, true, 1, null);
                    //FlipVerticaly(RevelView, true, 0.8, null);

                    RevelView.Hidden = false;
                    count++;
                }
                else
                {
                    //SlideHorizontaly(RevelView, false, true, 1, null);
                    //SlideVerticaly(RevelView, false, true, 1, null);
                    //FadeAnimation(RevelView, false, 1, null);
                    Zoom(RevelView, false, 0.8, null);
                    //Scale(RevelView, false, 1, null);
                    //Rotate(RevelView, false, true, 1, null);
                    //FlipVerticaly(RevelView, false, 0.7, null);

                    count = 1;
                }
            };


            lblName.Text         = Name;
            ProfilePicture.Image = UIImage.FromFile(Image);

            if (Status == true)
            {
                lblStatus.Text = "Online";
            }
            else
            {
                lblStatus.RemoveFromSuperview();
            }

            textSender.AttributedPlaceholder = new NSAttributedString("type message here...", null, UIColor.FromRGB(98, 107, 186));

            btnBack.TouchUpInside += (sender, e) =>
            {
                this.NavigationController.PopViewController(true);
            };
        }
Ejemplo n.º 47
0
        public override void ViewDidLayoutSubviews()
        {
            base.ViewDidLayoutSubviews();


            var img = UIImage.FromBundle("camion");

            var camion = new CALayer();

            camion.Contents                    = img.CGImage;
            camion.Bounds                      = new CoreGraphics.CGRect(x: 0, y: 0, width: 92, height: 92);
            camion.Position                    = new CoreGraphics.CGPoint(x: View.Center.X, y: View.Center.Y - 20);
            ContenidoVista.Layer.Mask          = camion;
            ContenidoVista.Layer.MasksToBounds = true;

            /*
             *  var bird = new CALayer();
             *  smileMask.contents = UIImage(named: "smiley face")?.cgImage
             *  smileMask.bounds = CGRect(x: 0, y: 0, width: 92, height: 92)
             *  smileMask.position = CGPoint(x: view.center.x, y: view.center.y-20)
             *  contentView.layer.mask = smileMask
             *  contentView.layer.masksToBounds = true
             */

            // MARK: - Smile Animation

            /*
             * 1. duration
             * 2. timing curve
             * 3. keyframes
             * 4. keyframe order
             * 5. apply animation
             */

            /*
             *
             * var animation = CAKeyframeAnimation(keyPath: "bounds")
             * animation.duration = 1
             * animation.timingFunctions = [
             * CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut),
             * CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
             * ]
             *
             */

            var animation = CAKeyFrameAnimation.FromKeyPath("bounds");

            animation.Duration        = 1;
            animation.TimingFunctions = new CAMediaTimingFunction[] {
                CAMediaTimingFunction.FromName(CAMediaTimingFunction.EaseInEaseOut),
                CAMediaTimingFunction.FromName(CAMediaTimingFunction.EaseInEaseOut)
            };

            var keyframe1 = NSValue.FromCGRect(new CoreGraphics.CGRect(x: 0, y: 0, width: 80, height: 80));
            var keyframe2 = NSValue.FromCGRect(new CoreGraphics.CGRect(x: 0, y: 0, width: 65, height: 65));
            var keyframe3 = NSValue.FromCGRect(new CoreGraphics.CGRect(x: 0, y: 0, width: 5200, height: 5200));


            animation.Values = new NSObject[] {
                keyframe1,
                keyframe2,
                keyframe3
            };


            animation.KeyTimes = new NSNumber[] {
                NSNumber.FromFloat(0f),
                NSNumber.FromFloat(0.7f),
                NSNumber.FromFloat(1f)
            };

            /*
             *  contentView.layer.mask?.add(animation, forKey: "bounds")
             *  contentView.layer.mask?.bounds = CGRect(x: 0, y: 0, width: 2600, height: 2600)
             */

            ContenidoVista.Layer.Mask.AddAnimation(animation, "bounds");
            ContenidoVista.Layer.Mask.Bounds = new CoreGraphics.CGRect(x: 0, y: 0, width: 5200, height: 5200);

            // contentView.transform = CGAffineTransform(scaleX: 1.1, y: 1.1)

            ContenidoVista.Transform = CoreGraphics.CGAffineTransform.MakeScale(1.1f, 1.1f); //Scale(1.1f, sy: 1.1f);

            /* UIView.animate(withDuration: 0.4, delay: 0.8, usingSpringWithDamping: 1, initialSpringVelocity: 16, options: .curveEaseInOut, animations: {
             *   self.contentView.transform = CGAffineTransform(scaleX: 1, y: 1)
             * }, completion: nil)
             */

            UIView.Animate(0.4, 0.8, UIViewAnimationOptions.CurveEaseInOut, HandleAction, HandleAction1);
        }
Ejemplo n.º 48
0
 public ClockLayer(CALayer other)
     : base(other)
 {
 }
Ejemplo n.º 49
0
 private static void Render(CALayer target, IViewport viewport, IEnumerable <ILayer> layers)
 {
     layers = layers.ToList();
     VisibleFeatureIterator.IterateLayers(viewport, layers, (v, s, f) => RenderGeometry(target, v, s, f));
 }
Ejemplo n.º 50
0
 public override void Clone(CALayer other)
 {
     ClockColor = ((ClockLayer)other).ClockColor;
     base.Clone(other);
 }
Ejemplo n.º 51
0
        public static CALayer ComposeText(string text, Fnt font, byte[] palette, int width, int height, int offset)
        {
            if (font == null)
            {
                Console.WriteLine("aiiiieeee");
            }

            int i;

            /* create a run of text, for now ignoring any control codes in the string */
            StringBuilder run = new StringBuilder();

            if (text != null)
            {
                for (i = 0; i < text.Length; i++)
                {
                    if (text[i] == 0x0a /* allow newlines */ ||
                        !Char.IsControl(text[i]))
                    {
                        run.Append(text[i]);
                    }
                }
            }

            string rs = run.ToString();

            byte[] r = Encoding.ASCII.GetBytes(rs);

            int x, y;
            int text_height, text_width;

            /* measure the text first, optionally wrapping at width */
            text_width = text_height = 0;
            x          = y = 0;

            for (i = 0; i < r.Length; i++)
            {
                int glyph_width = 0;

                if (r[i] != 0x0a)                 /* newline */
                {
                    if (r[i] == 0x20)             /* space */
                    {
                        glyph_width = font.SpaceSize;
                    }
                    else
                    {
                        Glyph g = font[r[i] - 1];

                        glyph_width = g.Width + g.XOffset;
                    }
                }

                if (r[i] == 0x0a ||
                    (width != -1 && x + glyph_width > width))
                {
                    if (x > text_width)
                    {
                        text_width = x;
                    }
                    x            = 0;
                    text_height += font.LineSize;
                }

                x += glyph_width;
            }

            if (x > text_width)
            {
                text_width = x;
            }
            text_height += font.LineSize;

            CALayer layer = CALayer.Create();

            layer.AnchorPoint = new PointF(0, 0);
            layer.Bounds      = new RectangleF(0, 0, text_width, text_height);

            /* the draw it */
            x = 0;
            y = text_height;
            for (i = 0; i < r.Length; i++)
            {
                int   glyph_width = 0;
                Glyph g           = null;

                if (r[i] != 0x0a)                 /* newline */
                {
                    if (r[i] == 0x20)             /* space */
                    {
                        glyph_width = font.SpaceSize;
                    }
                    else
                    {
                        g           = font[r[i] - 1];
                        glyph_width = g.Width + g.XOffset;

                        CALayer gl = RenderGlyph(font, g, palette, offset);
                        gl.AnchorPoint = new PointF(0, 0);
                        gl.Position    = new PointF(x, y - g.Height - g.YOffset);
                        layer.AddSublayer(gl);
                    }
                }

                if (r[i] == 0x0a ||
                    x + glyph_width > text_width)
                {
                    x  = 0;
                    y -= font.LineSize;
                }

                x += glyph_width;
            }

            return(layer);
        }
        private void LoadHeaderView()
        {
            NavigationDrawer = new SFNavigationDrawer
            {
                BackgroundColor = UIColor.Clear,
                ContentView     = content
            };

            menuButton = new UIButton();
            menuButton.SetBackgroundImage(new UIImage("Images/menu.png"), UIControlState.Normal);

            if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad)
            {
                NavigationDrawer.DrawerWidth = (this.View.Bounds.Width * 40) / 100;
            }
            else
            {
                NavigationDrawer.DrawerWidth = (this.View.Bounds.Width * 75) / 100;
            }

            NavigationDrawer.DrawerHeight = this.View.Bounds.Height;

            HeaderView = new UIView
            {
                BackgroundColor = UIColor.FromRGBA(249.0f / 255.0f, 78.0f / 255.0f, 56.0f / 255.0f, 0.97f)
            };

            userImg = new UIImageView
            {
                Image = new UIImage("Controls/synclogo.png")
            };

            version = new UILabel
            {
                Text          = "Version " + NSUserDefaults.StandardUserDefaults.ValueForKey(new NSString("VersionNumber")),
                Font          = UIFont.FromName("Helvetica", 12f),
                TextColor     = UIColor.White,
                TextAlignment = UITextAlignment.Left
            };
            HeaderView.AddSubview(version);

            yellowSeperater = new UIView
            {
                BackgroundColor = UIColor.FromRGB(255.0f / 255.0f, 198.0f / 255.0f, 14.0f / 255.0f)
            };
            HeaderView.AddSubview(yellowSeperater);

            headerDetails = new UILabel
            {
                LineBreakMode = UILineBreakMode.WordWrap,
                Lines         = 0,
                Text          = "The toolkit contains all the components that are typically required for building line-of-business applications for IOS",
                TextColor     = UIColor.White,
                Font          = UIFont.FromName("Helvetica", 18f)
            };
            HeaderView.AddSubview(headerDetails);

            HeaderView.AddSubview(userImg);

            Table = new UITableView(new CGRect(0, 20, NavigationDrawer.DrawerWidth, this.View.Frame.Height))
            {
                SeparatorColor = UIColor.Clear
            };

            NavigationTableSource tablesource = new NavigationTableSource(this, GetTableItems())
            {
                Customize = false
            };

            Table.Source          = tablesource;
            Table.BackgroundColor = UIColor.Clear;
            centerview            = new UIView
            {
                Table
            };

            centerview.BackgroundColor = UIColor.Clear;

            NavigationDrawer.Position = SFNavigationDrawerPosition.SFNavigationDrawerPositionLeft;

            menuButton.TouchDown += (object sender, System.EventArgs e) =>
            {
                HideDrawer(false);
            };

            header = new UIView
            {
                BackgroundColor = UIColor.FromRGB(0, 122.0f / 255.0f, 238.0f / 255.0f)
            };

            title = new UILabel
            {
                TextColor = UIColor.White,
                Text      = "Syncfusion Xamarin Samples",
                Font      = UIFont.FromName("HelveticaNeue-Medium", 16f)
            };

            flowLayoutAllControls = new UICollectionViewFlowLayout
            {
                MinimumLineSpacing = 5,
                ScrollDirection    = UICollectionViewScrollDirection.Vertical
            };

            collectionViewAllControls = new UICollectionView(CGRect.Empty, flowLayoutAllControls);
            collectionViewAllControls.RegisterClassForCell(typeof(UICollectionViewCell), "controlCell");
            collectionViewAllControls.DataSource      = new AllControlsCollectionSource(Controls);
            collectionViewAllControls.Delegate        = new AllControlsCollectionDelegate(this);
            collectionViewAllControls.BackgroundColor = Utility.BackgroundColor;

            UINib nibAllControls = UINib.FromName("ControlCell_9", null);

            collectionViewAllControls.RegisterNibForCell(nibAllControls, "controlCell");

            BottomBorder = new CALayer
            {
                BorderWidth = 1,
                BorderColor = UIColor.FromRGB(213.0f / 255.0f, 213.0f / 255.0f, 213.0f / 255.0f).CGColor,
                Hidden      = true
            };

            content.AddSubview(header);
            content.AddSubview(menuButton);
            content.AddSubview(title);
            content.AddSubview(collectionViewAllControls);

            overlay = new CALayer
            {
                ZPosition       = 1000,
                Hidden          = true,
                BackgroundColor = UIColor.FromRGBA(0.0f / 255.0f, 0.0f / 255.0f, 0.0f / 255.0f, 0.05f).CGColor
            };
            content.Layer.AddSublayer(overlay);

            this.View.AddSubview(NavigationDrawer);
        }
Ejemplo n.º 53
0
        void OnUpdateNativeControl(CALayer caLayer)
        {
            var view   = Renderer.Element;
            var uiview = Renderer.NativeView;

            if (view == null || view.Batched)
            {
                return;
            }

            bool shouldInteract;

            if (view is Layout layout)
            {
                if (layout.InputTransparent)
                {
                    shouldInteract = !layout.CascadeInputTransparent;
                }
                else
                {
                    shouldInteract = layout.IsEnabled;
                }
            }
            else
            {
                shouldInteract = !view.InputTransparent && view.IsEnabled;
            }

            if (_isInteractive != shouldInteract)
            {
#if __MOBILE__
                uiview.UserInteractionEnabled = shouldInteract;
#endif
                _isInteractive = shouldInteract;
            }

            var boundsChanged = _lastBounds != view.Bounds && TrackFrame;
#if !__MOBILE__
            var viewParent          = view.RealParent as VisualElement;
            var parentBoundsChanged = _lastParentBounds != (viewParent == null ? Rectangle.Zero : viewParent.Bounds);
#else
            var thread = !boundsChanged && !caLayer.Frame.IsEmpty && Application.Current?.OnThisPlatform()?.GetHandleControlUpdatesOnMainThread() == false;
#endif
            var anchorX      = (float)view.AnchorX;
            var anchorY      = (float)view.AnchorY;
            var translationX = (float)view.TranslationX;
            var translationY = (float)view.TranslationY;
            var rotationX    = (float)view.RotationX;
            var rotationY    = (float)view.RotationY;
            var rotation     = (float)view.Rotation;
            var scale        = (float)view.Scale;
            var scaleX       = (float)view.ScaleX * scale;
            var scaleY       = (float)view.ScaleY * scale;
            var width        = (float)view.Width;
            var height       = (float)view.Height;
            var x            = (float)view.X + (float)CompressedLayout.GetHeadlessOffset(view).X;
            var y            = (float)view.Y + (float)CompressedLayout.GetHeadlessOffset(view).Y;
            var opacity      = (float)view.Opacity;
            var isVisible    = view.IsVisible;

            var updateTarget = Interlocked.Increment(ref _updateCount);

            void update()
            {
                if (updateTarget != _updateCount)
                {
                    return;
                }
#if __MOBILE__
                var visualElement = view;
#endif
                var parent = view.RealParent;

                var shouldRelayoutSublayers = false;
                if (isVisible && caLayer.Hidden)
                {
#if !__MOBILE__
                    uiview.Hidden = false;
#endif
                    caLayer.Hidden = false;
                    if (!caLayer.Frame.IsEmpty)
                    {
                        shouldRelayoutSublayers = true;
                    }
                }

                if (!isVisible && !caLayer.Hidden)
                {
#if !__MOBILE__
                    uiview.Hidden = true;
#endif
                    caLayer.Hidden          = true;
                    shouldRelayoutSublayers = true;
                }

                // ripe for optimization
                var transform = CATransform3D.Identity;

#if __MOBILE__
                bool shouldUpdate = (!(visualElement is Page) || visualElement is ContentPage) && width > 0 && height > 0 && parent != null && boundsChanged;
#else
                // We don't care if it's a page or not since bounds of the window can change
                // TODO: Find why it doesn't work to check if the parentsBounds changed  and remove true;
                parentBoundsChanged = true;
                bool shouldUpdate = width > 0 && height > 0 && parent != null && (boundsChanged || parentBoundsChanged);
#endif
                // Dont ever attempt to actually change the layout of a Page unless it is a ContentPage
                // iOS is a really big fan of you not actually modifying the View's of the UIViewControllers
                if (shouldUpdate && TrackFrame)
                {
#if __MOBILE__
                    var target = new RectangleF(x, y, width, height);
#else
                    var   visualParent = parent as VisualElement;
                    float newY         = visualParent == null ? y : Math.Max(0, (float)(visualParent.Height - y - view.Height));
                    var   target       = new RectangleF(x, newY, width, height);
#endif

                    // must reset transform prior to setting frame...
                    caLayer.Transform = transform;
                    uiview.Frame      = target;
                    if (shouldRelayoutSublayers)
                    {
                        caLayer.LayoutSublayers();
                    }
                }
                else if (width <= 0 || height <= 0)
                {
                    //TODO: FInd why it doesn't work
#if __MOBILE__
                    caLayer.Hidden = true;
#endif
                    return;
                }
#if __MOBILE__
                caLayer.AnchorPoint = new PointF(anchorX, anchorY);
#else
                caLayer.AnchorPoint = new PointF(anchorX - 0.5f, anchorY - 0.5f);
#endif
                caLayer.Opacity = opacity;
                const double epsilon = 0.001;

                // position is relative to anchor point
                if (Math.Abs(anchorX - .5) > epsilon)
                {
                    transform = transform.Translate((anchorX - .5f) * width, 0, 0);
                }
                if (Math.Abs(anchorY - .5) > epsilon)
                {
                    transform = transform.Translate(0, (anchorY - .5f) * height, 0);
                }

                if (Math.Abs(translationX) > epsilon || Math.Abs(translationY) > epsilon)
                {
                    transform = transform.Translate(translationX, translationY, 0);
                }

                if (Math.Abs(scaleX - 1) > epsilon || Math.Abs(scaleY - 1) > epsilon)
                {
                    transform = transform.Scale(scaleX, scaleY, scale);
                }

                // not just an optimization, iOS will not "pixel align" a view which has m34 set
                if (Math.Abs(rotationY % 180) > epsilon || Math.Abs(rotationX % 180) > epsilon)
                {
                    transform.m34 = 1.0f / -400f;
                }

                if (Math.Abs(rotationX % 360) > epsilon)
                {
                    transform = transform.Rotate(rotationX * (float)Math.PI / 180.0f, 1.0f, 0.0f, 0.0f);
                }
                if (Math.Abs(rotationY % 360) > epsilon)
                {
                    transform = transform.Rotate(rotationY * (float)Math.PI / 180.0f, 0.0f, 1.0f, 0.0f);
                }

                transform = transform.Rotate(rotation * (float)Math.PI / 180.0f, 0.0f, 0.0f, 1.0f);

                if (Foundation.NSThread.IsMain)
                {
                    caLayer.Transform = transform;
                    return;
                }
                CoreFoundation.DispatchQueue.MainQueue.DispatchAsync(() =>
                {
                    caLayer.Transform = transform;
                });
            }

#if __MOBILE__
            if (thread)
            {
                CADisplayLinkTicker.Default.Invoke(update);
            }
            else
            {
                update();
            }
#else
            update();
#endif

            _lastBounds = view.Bounds;
#if !__MOBILE__
            _lastParentBounds = viewParent?.Bounds ?? Rectangle.Zero;
#endif
        }
Ejemplo n.º 54
0
        /// <summary>
        /// Creates and add 2 layers for ImageBrush background
        /// </summary>
        /// <param name="fullArea">The full area available (includes the border)</param>
        /// <param name="insideArea">The "inside" of the border (excludes the border)</param>
        /// <param name="layer">The layer in which the image layers will be added</param>
        /// <param name="sublayers">List of layers to keep all references</param>
        /// <param name="insertionIndex">Where in the layer the new layers will be added</param>
        /// <param name="imageBrush">The ImageBrush containing all the image properties (UIImage, Stretch, AlignmentX, etc.)</param>
        /// <param name="fillMask">Optional mask layer (for when we use rounded corners)</param>
        private static void CreateImageBrushLayers(CGRect fullArea, CGRect insideArea, CALayer layer, List <CALayer> sublayers, ref int insertionIndex, ImageBrush imageBrush, CAShapeLayer fillMask)
        {
            var uiImage = imageBrush.ImageSource.ImageData;

            // This layer is the one we apply the mask on. It's the full size of the shape because the mask is as well.
            var imageContainerLayer = new CALayer
            {
                Frame           = fullArea,
                Mask            = fillMask,
                BackgroundColor = new CGColor(0, 0, 0, 0),
                MasksToBounds   = true,
            };

            var imageFrame = imageBrush.GetArrangedImageRect(uiImage.Size, insideArea).ToCGRect();

            // This is the layer with the actual image in it. Its frame is the inside of the border.
            var imageLayer = new CALayer
            {
                Contents      = uiImage.CGImage,
                Frame         = imageFrame,
                MasksToBounds = true,
            };

            imageContainerLayer.AddSublayer(imageLayer);
            sublayers.Add(imageLayer);

            layer.InsertSublayer(imageContainerLayer, insertionIndex++);
            sublayers.Add(imageContainerLayer);
        }
Ejemplo n.º 55
0
        public Trackball()
        {
            SFChart chart = new SFChart();

            chart.ColorModel.Palette = SFChartColorPalette.Natural;

            SFCategoryAxis primaryAxis = new SFCategoryAxis();

            primaryAxis.AxisLineOffset     = 2;
            primaryAxis.PlotOffset         = 5;
            primaryAxis.ShowMajorGridLines = false;
            chart.PrimaryAxis = primaryAxis;

            SFNumericalAxis secondaryAxis = new SFNumericalAxis();

            secondaryAxis.MajorTickStyle.LineSize = 0;
            secondaryAxis.AxisLineStyle.LineWidth = 0;
            secondaryAxis.Minimum = new NSNumber(25);
            secondaryAxis.Maximum = new NSNumber(50);
            chart.SecondaryAxis   = secondaryAxis;
            ChartViewModel dataModel = new ChartViewModel();

            SFLineSeries series1 = new SFLineSeries();

            series1.ItemsSource  = dataModel.LineSeries1;
            series1.XBindingPath = "XValue";
            series1.YBindingPath = "YValue";
            series1.Label        = "Germany";
            series1.LineWidth    = 3;
            chart.Series.Add(series1);

            SFLineSeries series2 = new SFLineSeries();

            series2.ItemsSource  = dataModel.LineSeries2;
            series2.XBindingPath = "XValue";
            series2.YBindingPath = "YValue";
            series2.Label        = "England";
            series2.LineWidth    = 3;
            chart.Series.Add(series2);

            SFLineSeries series3 = new SFLineSeries();

            series3.ItemsSource  = dataModel.LineSeries3;
            series3.XBindingPath = "XValue";
            series3.YBindingPath = "YValue";
            series3.Label        = "France";
            series3.LineWidth    = 3;
            chart.Series.Add(series3);

            label               = new UILabel();
            label.Text          = "Press and hold to enable trackball";
            label.Font          = UIFont.FromName("Helvetica", 12f);
            label.TextAlignment = UITextAlignment.Center;
            label.LineBreakMode = UILineBreakMode.WordWrap;
            label.Lines         = 2;

            label.BackgroundColor = UIColor.FromRGB(249, 249, 249);
            label.TextColor       = UIColor.FromRGB(79, 86, 91);

            CALayer topLine = new CALayer();

            topLine.Frame           = new CGRect(0, 0, UIScreen.MainScreen.ApplicationFrame.Width, 0.5);
            topLine.BackgroundColor = UIColor.FromRGB(178, 178, 178).CGColor;
            label.Layer.AddSublayer(topLine);

            chart.Legend.Visible                = true;
            chart.Legend.IconWidth              = 14;
            chart.Legend.IconHeight             = 14;
            chart.Legend.ToggleSeriesVisibility = true;
            chart.Legend.DockPosition           = SFChartLegendPosition.Bottom;

            chart.AddChartBehavior(new SFChartTrackballBehavior());

            this.AddSubview(chart);
            this.AddSubview(label);
        }
Ejemplo n.º 56
0
        /// <summary>
        /// Creates and add 2 layers for LinearGradientBrush background
        /// </summary>
        /// <param name="fullArea">The full area available (includes the border)</param>
        /// <param name="insideArea">The "inside" of the border (excludes the border)</param>
        /// <param name="layer">The layer in which the gradient layers will be added</param>
        /// <param name="sublayers">List of layers to keep all references</param>
        /// <param name="insertionIndex">Where in the layer the new layers will be added</param>
        /// <param name="linearGradientBrush">The LinearGradientBrush</param>
        /// <param name="fillMask">Optional mask layer (for when we use rounded corners)</param>
        private static void CreateLinearGradientBrushLayers(CGRect fullArea, CGRect insideArea, CALayer layer, List <CALayer> sublayers, ref int insertionIndex, LinearGradientBrush linearGradientBrush, CAShapeLayer fillMask)
        {
            // This layer is the one we apply the mask on. It's the full size of the shape because the mask is as well.
            var gradientContainerLayer = new CALayer
            {
                Frame           = fullArea,
                Mask            = fillMask,
                BackgroundColor = new CGColor(0, 0, 0, 0),
                MasksToBounds   = true,
            };

            var gradientFrame = new CGRect(new CGPoint(insideArea.X, insideArea.Y), insideArea.Size);

            // This is the layer with the actual gradient in it. Its frame is the inside of the border.
            var gradientLayer = linearGradientBrush.GetLayer(insideArea.Size);

            gradientLayer.Frame         = gradientFrame;
            gradientLayer.MasksToBounds = true;

            gradientContainerLayer.AddSublayer(gradientLayer);
            sublayers.Add(gradientLayer);

            layer.InsertSublayer(gradientContainerLayer, insertionIndex++);
            sublayers.Add(gradientContainerLayer);
        }
Ejemplo n.º 57
0
        private void DrawFaces(CIFeature[] features,
                               CGRect clearAperture,
                               UIDeviceOrientation deviceOrientation)
        {
            var pLayer         = this.previewLayer as AVCaptureVideoPreviewLayer;
            var subLayers      = pLayer.Sublayers;
            var subLayersCount = subLayers.Count();

            var featureCount = features.Count();

            nint currentSubLayer = 0, currentFeature = 0;

            CATransaction.Begin();
            CATransaction.DisableActions = true;
            foreach (var layer in subLayers)
            {
                if (layer.Name == "FaceLayer")
                {
                    layer.Hidden = true;
                }
            }

            Console.WriteLine("Feature: " + featureCount);
            if (featureCount == 0)
            {
                CATransaction.Commit();
                return;
            }

            var parentFameSize = this.HomeView.Frame.Size;
            var gravity        = pLayer.VideoGravity;
            var isMirrored     = pLayer.Connection.VideoMirrored;
            var previewBox     = VideoPreviewBoxForGravity(gravity, parentFameSize, clearAperture.Size);


            foreach (var feature in features)
            {
                // find the correct position for the square layer within the previewLayer
                // the feature box originates in the bottom left of the video frame.
                // (Bottom right if mirroring is turned on)
                CGRect faceRect = feature.Bounds;

                // flip preview width and height
                var tempCGSize = new CGSize(faceRect.Size.Height, faceRect.Size.Width);

                faceRect.Size = tempCGSize;
                faceRect.X    = faceRect.Y;
                faceRect.Y    = faceRect.X;

                //// scale coordinates so they fit in the preview box, which may be scaled
                var widthScaleBy  = previewBox.Size.Width / clearAperture.Size.Height;
                var heightScaleBy = previewBox.Size.Height / clearAperture.Size.Width;
                var newWidth      = faceRect.Size.Width * widthScaleBy;
                var newheight     = faceRect.Size.Height * heightScaleBy;
                faceRect.Size = new CGSize(newWidth, newheight);
                faceRect.X   *= widthScaleBy;
                faceRect.Y   *= heightScaleBy;

                if (isMirrored)
                {
                    faceRect.Offset(previewBox.X + previewBox.Size.Width - faceRect.Size.Width - (faceRect.X * 2),
                                    previewBox.Y);
                }
                else
                {
                    faceRect.Offset(previewBox.X, previewBox.Y);
                }


                while (featureLayer != null && currentSubLayer < subLayersCount)
                {
                    CALayer currentLayer = subLayers[currentSubLayer++];
                    if (currentLayer.Name == "FaceLayer")
                    {
                        featureLayer        = currentLayer;
                        currentLayer.Hidden = false;
                    }
                }

                if (featureLayer == null)
                {
                    featureLayer          = new CALayer();
                    featureLayer.Contents = borderImage.CGImage;
                    featureLayer.Name     = "FaceLayer";
                    this.previewLayer.AddSublayer(featureLayer);
                }

                featureLayer.Frame = faceRect;


                switch (deviceOrientation)
                {
                case UIDeviceOrientation.Portrait:
                    featureLayer.AffineTransform = CGAffineTransform.MakeRotation(DegreesToRadians(0));
                    break;

                case UIDeviceOrientation.PortraitUpsideDown:
                    featureLayer.AffineTransform = (CGAffineTransform.MakeRotation(DegreesToRadians(180)));
                    break;

                case UIDeviceOrientation.LandscapeLeft:
                    featureLayer.AffineTransform = CGAffineTransform.MakeRotation(DegreesToRadians(90));
                    break;

                case UIDeviceOrientation.LandscapeRight:
                    featureLayer.AffineTransform = CGAffineTransform.MakeRotation(DegreesToRadians(-90));

                    break;

                case UIDeviceOrientation.FaceUp:
                case UIDeviceOrientation.FaceDown:
                default:
                    break;     // leave the layer in its last known orientation
                }
                currentFeature++;
            }

            CATransaction.Commit();
        }
Ejemplo n.º 58
0
 public void Include(CALayer l)
 {
     l.BorderColor = l.BorderColor;
 }
        private void Initilizeview()
        {
            #region Header

            titleLabel               = new UILabel();
            titleLabel.Text          = "Functions Library";
            titleLabel.Font          = UIFont.FromName("Helvetica-Bold", 25f);
            titleLabel.TextAlignment = UITextAlignment.Center;

            descripLabel               = new UILabel();
            descripLabel.Text          = "This sample demonstrates the calculation using various Excel-like functions.";
            descripLabel.Lines         = 0;
            descripLabel.LineBreakMode = UILineBreakMode.WordWrap;
            descripLabel.Font          = UIFont.FromName("Helvetica", 12f);

            #endregion

            #region Functions

            functionLabel      = new UILabel();
            functionLabel.Text = "Select a function";
            functionLabel.Font = UIFont.FromName("Helvetica", 14f);

            pickerTextView      = new UITextField();
            pickerTextView.Text = "ABS";
            pickerTextView.Font = UIFont.FromName("Helvetica", 14f);
            FunctionsLibraryViewModel model = new FunctionsLibraryViewModel(formulaText, pickerTextView, this);
            functionsPicker          = new UIPickerView();
            functionsPicker.Model    = model;
            pickerTextView.InputView = functionsPicker;

            #endregion

            #region GridView

            label00 = CreateLabel("");
            labelA0 = CreateLabel("A");
            labelB0 = CreateLabel("B");
            labelC0 = CreateLabel("C");
            label01 = CreateLabel("1");
            label02 = CreateLabel("2");
            label03 = CreateLabel("3");
            label04 = CreateLabel("4");
            label05 = CreateLabel("5");
            textA1  = CreateTextField("32");
            textB1  = CreateTextField("50");
            textC1  = CreateTextField("10");
            textA2  = CreateTextField("12");
            textB2  = CreateTextField("24");
            textC2  = CreateTextField("90");
            textA3  = CreateTextField("88");
            textB3  = CreateTextField("-22");
            textC3  = CreateTextField("37");
            textA4  = CreateTextField("73");
            textB4  = CreateTextField("91");
            textC4  = CreateTextField("21");
            textA5  = CreateTextField("63");
            textB5  = CreateTextField("29");
            textC5  = CreateTextField("44");

            #endregion

            #region Formula

            formulaLabel      = new UILabel();
            formulaLabel.Text = "Formula";
            formulaLabel.Font = UIFont.FromName("Helvetica", 14f);

            formulaText.BorderStyle = UITextBorderStyle.Line;
            formulaText.Text        = "=ABS(B3)";
            formulaText.Font        = UIFont.FromName("Helvetica", 14f);
            formulaText.ResignFirstResponder();

            #endregion

            #region Compute

            calculateButton = new UIButton();
            calculateButton.SetTitle("Compute", UIControlState.Normal);
            calculateButton.Layer.BorderWidth  = 1;
            calculateButton.Layer.CornerRadius = 4;
            calculateButton.SetTitleColor(UIColor.Black, UIControlState.Highlighted);
            calculateButton.BackgroundColor = UIColor.LightGray;
            calculateButton.TouchUpInside  += CalculateButton_TouchUpInside;

            #endregion

            #region Result

            calculatedLabel      = new UILabel();
            calculatedLabel.Text = "Computed Value";
            calculatedLabel.Font = UIFont.FromName("Helvetica", 14f);

            layer = new CALayer()
            {
                BorderWidth = 1, BorderColor = UIColor.Black.CGColor
            };

            calculatedText      = new UILabel();
            calculatedText.Font = UIFont.FromName("Helvetica", 14f);
            calculatedText.Layer.AddSublayer(layer);

            #endregion

            AddSubview(titleLabel);
            AddSubview(descripLabel);
            AddSubview(functionLabel);
            AddSubview(pickerTextView);

            AddSubview(label00);
            AddSubview(labelA0);
            AddSubview(labelB0);
            AddSubview(labelC0);

            AddSubview(label01);
            AddSubview(textA1);
            AddSubview(textB1);
            AddSubview(textC1);

            AddSubview(label02);
            AddSubview(textA2);
            AddSubview(textB2);
            AddSubview(textC2);

            AddSubview(label03);
            AddSubview(textA3);
            AddSubview(textB3);
            AddSubview(textC3);

            AddSubview(label04);
            AddSubview(textA4);
            AddSubview(textB4);
            AddSubview(textC4);

            AddSubview(label05);
            AddSubview(textA5);
            AddSubview(textB5);
            AddSubview(textC5);

            AddSubview(formulaLabel);
            AddSubview(formulaText);

            AddSubview(calculateButton);
            AddSubview(calculatedLabel);
            AddSubview(calculatedText);
        }
Ejemplo n.º 60
0
 internal void RemoveStatusLayer(CALayer statusLayer)
 {
     RemoveTrackingArea(layerToStatus [statusLayer.Name].TrackingArea);
     layerToStatus.Remove(statusLayer.Name);
     RepositionStatusLayers();
 }