protected override void onLayout(CGRect newPosition, bool parentHidden) { // Reposition the layer if (_layer != null) { bool newHidden = parentHidden || !Visible; if (newHidden != _layer.Hidden) { // If we're changing the visibility, disable animations since // the old rectangle for the position was probably wrong, resulting in // weird animation as it's repositioned. CATransaction.Begin(); CATransaction.DisableActions = true; _layer.Hidden = newHidden; _layer.Frame = newPosition; CATransaction.Commit(); } else { if (!_layer.Hidden) { _layer.Frame = newPosition; } } } // Hide all subviews if (parentHidden || !Visible) { foreach (var v in SubViews) { v.Layout(CGRect.Empty, false); } return; } }
protected override void Window_DidResize(object sender, EventArgs e) { // get relative y-position of balls to use after superLayer frame is resized double[] yPos = new double[Balls.Length]; for (int i = 0; i < Balls.Length; i++) { yPos[i] = Balls[i].BallLayer.Frame.Y / BounceHelper.Height; } base.Window_DidResize(sender, e); CATransaction.Begin(); CATransaction.DisableActions = true; for (int i = 0; i < Balls.Length; i++) { Balls[i].InitLayer(); // need to preserve the y-position var frame = Balls[i].BallLayer.Frame; frame.Y = (nfloat)(BounceHelper.Height * yPos[i]); Balls[i].BallLayer.Frame = frame; Balls[i].BallLayer.SetNeedsDisplay(); } CATransaction.Commit(); }
public void ButtonDragged(ButtonView button, UITouch location) { CGPoint point = location.LocationInView(miniPadView); if (miniPadView.PointInside(point, null)) { if (!buttonDraggedToPad) { CATransaction.Begin(); CATransaction.AnimationDuration = 1; miniPadView.Layer.BorderColor = UIColor.Yellow.CGColor; miniPadView.Layer.BorderWidth = 2; CATransaction.Commit(); buttonDraggedToPad = true; if (!isVoiceOverSpeaking) { isVoiceOverSpeaking = true; UIAccessibility.PostNotification(UIAccessibilityPostNotification.Announcement, (NSString)"Memory object near the zombies, Lift to deploy"); } } } else { if (buttonDraggedToPad) { if (!isVoiceOverSpeaking) { isVoiceOverSpeaking = true; UIAccessibility.PostNotification(UIAccessibilityPostNotification.Announcement, (NSString)"Memory object outside iPad. Lift to Cancel"); } } buttonDraggedToPad = false; miniPadView.Layer.BorderWidth = 0; } }
public override bool ContinueTracking(UITouch touch, UIEvent uievent) { CGPoint touchPoint = (CGPoint)touch.LocationInView((UIView)this); // 1. determine by how much the user has dragged var delta = touchPoint.X - _previousTouchPoint.X; var valueDelta = (MaxValue - MinValue) * delta / _useableTrackLength; _previousTouchPoint = touchPoint; // 2. update the values if (_lowerKnobLayer.Highlighted) { RawLowValue += valueDelta; RawLowValue = (nfloat)Math.Min(Math.Max(RawLowValue, MinValue), HighValue); //(_lowerValue, _upperValue, _minimumValue); if (increment > 0) { LowValue = (int)(RawLowValue / increment) * increment; } else { LowValue = RawLowValue; } } if (_upperKnobLayer.Highlighted) { RawHighValue += valueDelta; RawHighValue = (nfloat)Math.Max(Math.Min(RawHighValue, MaxValue), LowValue); if (increment > 0) { HighValue = (int)(RawHighValue / increment) * increment; } else { HighValue = RawHighValue; } } // 3. Update the UI state CATransaction.Begin(); CATransaction.DisableActions = true; setLayerFrames(); CATransaction.Commit(); if (_lowerKnobLayer.Highlighted) { LowerSliderChanged(this, new EventArgs()); } else { UpperSliderChanged(this, new EventArgs()); } if (_lowerKnobLayer.Highlighted || _upperKnobLayer.Highlighted) { return(true); } return(false); //return true; }
/// <summary> /// Cloned in CoreTableSource /// </summary> public virtual void AnimateTabBar(bool?show, bool suspendTrackingDuringAnimation = false, bool force = false) { CoreUtility.ExecuteMethod("AnimateTabBar", delegate() { if (this.AutoHideControllerInstance != null) { if (!this.AutoHideControllerInstance.IsControllerVisible) { return; } } if (!force && (this.SuspendTabBarTracking || this.DisableTabBarTracking)) { return; } UITabBar tabBar = this.AutoHideTabBarController.TabBar; if (!OriginalTabBarFrame.HasValue) { OriginalTabBarFrame = tabBar.Frame; } tabBar.Layer.RemoveAnimation(DRAG_ANIMATION_NAME); if (show.HasValue) { if (suspendTrackingDuringAnimation) { this.SuspendTabBarTracking = true; } CATransaction.Begin(); CATransaction.CompletionBlock = new Action(delegate() { if (suspendTrackingDuringAnimation) // only ours { this.SuspendTabBarTracking = false; } this.BeginInvokeOnMainThread(delegate() { CoreUtility.ExecuteMethod("DraggingStarted.CompletionBlock", delegate() { if (AutoHideTabBarShouldBeHidden) { tabBar.Frame = new CGRect(tabBar.Frame.X, this.AutoHideTabBarController.View.Frame.Height, tabBar.Frame.Width, tabBar.Frame.Height); } else { tabBar.Frame = OriginalTabBarFrame.GetValueOrDefault(); } tabBar.Layer.RemoveAnimation(DRAG_ANIMATION_NAME); }); }); }); if (!show.Value) { // content going up AutoHideTabBarShouldBeHidden = true; AnimationBuilder .Begin(tabBar.Layer, DRAG_ANIMATION_NAME) .MoveTo(new CGPoint(tabBar.Layer.Frame.X, this.AutoHideTabBarController.View.Frame.Height), 0f, 0.3f) .Commit(); } else if (show.Value) { // content going down AutoHideTabBarShouldBeHidden = false; AnimationBuilder .Begin(tabBar.Layer, DRAG_ANIMATION_NAME) .MoveTo(OriginalTabBarFrame.Value.Location, 0f, 0.3f) .Commit(); } CATransaction.Commit(); } }); }
public override void StatusUpdated(NSDictionary status) { // In the status dictionary: // "FoundBarcodes" key is a NSSet of all discovered barcodes this scan session // "NewFoundBarcodes" is a NSSet of barcodes discovered in the most recent pass. // When a barcode is found, it is added to both sets. The NewFoundBarcodes // set is cleaned out each pass. // "Guidance" can be used to help guide the user through the process of discovering // a long barcode in sections. Currently only works for Code 39. // "Valid" is TRUE once there are valid barcode results. // "InRange" is TRUE if there's currently a barcode detected the viewfinder. The barcode // may not have been decoded yet. It is possible for barcodes to be found without // InRange ever being set. // Make the RedLaser stripe more vivid when Barcode is in Range. if (status == null) { return; } var range = status ["InRange"] as NSNumber; var inRange = range.BoolValue; CATransaction.Begin(); CATransaction.AnimationDuration = 1; if (inRange) { rectLayer.StrokeColor = UIColor.Green.CGColor; } else { rectLayer.StrokeColor = UIColor.White.CGColor; } CATransaction.Commit(); View.SetNeedsDisplay(); // Beep when we find a new code var newFoundBarcodes = status ["NewFoundBarcodes"] as NSSet; if (newFoundBarcodes != null && newFoundBarcodes.Count > 0) { if (!alertViewDelegate.IsOnView) { if (beepSound != null) { beepSound.Play(); } var barcode = newFoundBarcodes.ToArray <BarcodeResult> () [0]; new UIAlertView("A New Barcode Has Been Found!!\nCode: ", barcode.BarcodeString + "\nType: " + barcode.BarcodeType, alertViewDelegate, "Ok", null).Show(); } } var guidance = status ["Guidance"] as NSNumber; if (guidance == null) { return; } int guidanceLevel = guidance.Int32Value; if (guidanceLevel == 1) { lblCue.Text = @"Try moving the camera close to each part of the barcode"; } else if (guidanceLevel == 2) { lblCue.Text = status ["PartialBarcode"].ToString(); } else { lblCue.Text = @""; } }
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); }
public void DidOutputMetadataObjects(AVCaptureMetadataOutput captureOutput, AVMetadataObject[] faces, AVCaptureConnection connection) { List <int> unseen = faceViews.Keys.ToList(); List <int> seen = new List <int> (); CATransaction.Begin(); CATransaction.SetValueForKey(NSObject.FromObject(true), (NSString)(CATransaction.DisableActions.ToString())); foreach (var face in faces) { // HACK: int faceId = (face as AVMetadataFaceObject).FaceID; int faceId = (int)(face as AVMetadataFaceObject).FaceID; unseen.Remove(faceId); seen.Add(faceId); FaceView view; if (faceViews.ContainsKey(faceId)) { view = faceViews [faceId]; } else { view = new FaceView(); view.Layer.CornerRadius = 10; view.Layer.BorderWidth = 3; view.Layer.BorderColor = UIColor.Green.CGColor; previewView.AddSubview(view); faceViews.Add(faceId, view); view.Id = faceId; view.Callback = TouchCallBack; if (lockedFaceID != null) { view.Alpha = 0; } } AVMetadataFaceObject adjusted = (AVMetadataFaceObject)(previewView.Layer as AVCaptureVideoPreviewLayer).GetTransformedMetadataObject(face); view.Frame = adjusted.Bounds; } foreach (int faceId in unseen) { FaceView view = faceViews [faceId]; view.RemoveFromSuperview(); faceViews.Remove(faceId); if (faceId == lockedFaceID) { clearLockedFace(); } } if (lockedFaceID != null) { FaceView view = faceViews [lockedFaceID.GetValueOrDefault()]; // HACK: Cast resulting nfloat to float // float size = (float)Math.Max (view.Frame.Size.Width, view.Frame.Size.Height) / device.VideoZoomFactor; float size = (float)(Math.Max(view.Frame.Size.Width, view.Frame.Size.Height) / device.VideoZoomFactor); float zoomDelta = lockedFaceSize / size; float lockTime = (float)(CATransition.CurrentMediaTime() - this.lockTime); float zoomRate = (float)(Math.Log(zoomDelta) / lockTime); if (Math.Abs(zoomDelta) > 0.1) { device.RampToVideoZoom(zoomRate > 0 ? MaxZoom : 1, zoomRate); } } CATransaction.Commit(); }
//- (void)presentImage:(NSImage *)image; void PresentImage(NSImage image, string filename) { int animationSpeed = 3; CGRect superLayerBounds = View.Layer.Bounds; CGPoint center = new CGPoint(superLayerBounds.GetMidX(), superLayerBounds.GetMidY()); CGRect imageBounds = new CGRect(0, 0, image.Size.Width, image.Size.Height); nfloat X = (nfloat)random.Next((int)Math.Floor(imageBounds.Width / 2), (int)Math.Floor(superLayerBounds.GetMaxX() - imageBounds.Width / 2)); //(superLayerBounds.GetMaxX() - imageBounds.Width/2) * random.NextDouble(); nfloat Y = (nfloat)random.Next((int)Math.Floor(imageBounds.Height / 2), (int)Math.Floor(superLayerBounds.GetMaxY() - imageBounds.Height / 2)); //(superLayerBounds.GetMaxY() - imageBounds.Height/2) * random.NextDouble(); CGPoint randomPoint = new CGPoint(X, Y); CAMediaTimingFunction tf = CAMediaTimingFunction.FromName(CAMediaTimingFunction.EaseInEaseOut); // Animations for image layer CABasicAnimation posAnim = CABasicAnimation.FromKeyPath("position"); posAnim.From = NSValue.FromCGPoint(center); posAnim.Duration = animationSpeed; posAnim.TimingFunction = tf; CABasicAnimation bdsAnim = CABasicAnimation.FromKeyPath("bounds"); bdsAnim.From = NSValue.FromCGRect(CGRect.Empty); bdsAnim.Duration = animationSpeed; bdsAnim.TimingFunction = tf; // Image layer CALayer layer = new CALayer(); layer.Contents = image.CGImage; layer.Position = center; layer.ZPosition = random.Next(-100, 99); layer.Actions = NSDictionary.FromObjectsAndKeys(new NSObject[] { posAnim, bdsAnim }, new NSObject[] { new NSString("position"), new NSString("bounds") }); // Animation for text layer CATransform3D scale = CATransform3D.MakeScale(0.0f, 0.0f, 0.0f); CABasicAnimation tScaleAnim = CABasicAnimation.FromKeyPath("transform"); tScaleAnim.From = NSValue.FromCATransform3D(scale); tScaleAnim.Duration = animationSpeed; tScaleAnim.TimingFunction = tf; // text layer CATextLayer fileNameLayer = new CATextLayer(); fileNameLayer.FontSize = 24; fileNameLayer.ForegroundColor = NSColor.White.CGColor; SetText(" " + filename + " ", fileNameLayer); fileNameLayer.Transform = scale; fileNameLayer.Position = CGPoint.Empty; fileNameLayer.AnchorPoint = CGPoint.Empty; fileNameLayer.ShadowColor = NSColor.Black.CGColor; fileNameLayer.ShadowOffset = new CGSize(5, 5); fileNameLayer.ShadowOpacity = 1.0f; fileNameLayer.ShadowRadius = 0.0f; fileNameLayer.BorderColor = NSColor.White.CGColor; fileNameLayer.BorderWidth = 1.0f; fileNameLayer.Actions = NSDictionary.FromObjectsAndKeys(new NSObject[] { tScaleAnim }, new NSObject[] { new NSString("transform") }); layer.AddSublayer(fileNameLayer); View.Layer.AddSublayer(layer); CATransaction.Begin(); layer.Position = randomPoint; layer.Bounds = imageBounds; fileNameLayer.Transform = CATransform3D.Identity; CATransaction.Commit(); }
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; } if (delayMilliseconds > 0) { // Note: We must make sure to use the time relative to the 'layer', otherwise we might introduce a random delay and the animations // will run twice (once "managed" while updating the DP, and a second "native" using this animator) _animation.BeginTime = layer.ConvertTimeFromLayer(CAAnimation.CurrentMediaTime() + delayMilliseconds / __millisecondsPerSecond, null); } _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) => { // This will disable the transform while the native animation handles it // It must be the first thing we do when the animation starts // (However we have to wait for the first frame in order to not remove the transform while waiting for the BeginTime) _prepare?.Invoke(); 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(); _cleanup?.Invoke(); 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); }
public virtual void refreshShapes() { // TODO: dunno why this is necessary; this.background.SetNeedsLayout(); this.background.LayoutIfNeeded(); if (popup != null) { this.popup.LayoutIfNeeded(); } if (connector != null) { this.connector.LayoutIfNeeded(); } var testPath = new UIBezierPath(); var edgePath = new UIBezierPath(); var unitSquare = new CGRect(0, 0, 1, 1); // TODO: withUnder; Func <KeyboardKeyBackground, UIBezierPath, UIBezierPath, int> addCurves = (fromShape, toPath, toEdgePaths) => { var shape = fromShape; if (shape != null) { var path = shape.fillPath; var translatedUnitSquare_ = this.displayView.ConvertRectFromView(unitSquare, fromView: shape); var transformFromShapeToView_ = CGAffineTransform.MakeTranslation((CGFloat)translatedUnitSquare_.Location.X, (CGFloat)translatedUnitSquare_.Location.Y); path.ApplyTransform(transformFromShapeToView_); if (path != null) { toPath.AppendPath(path); } var edgePaths = shape.edgePaths; if (edgePaths != null) { foreach (var anEdgePath in edgePaths) { var editablePath = anEdgePath; editablePath.ApplyTransform(transformFromShapeToView_); toEdgePaths.AppendPath(editablePath); } } } return(0); }; addCurves(this.popup, testPath, edgePath); addCurves(this.connector, testPath, edgePath); var shadowPath = UIBezierPath.FromPath(path: testPath.CGPath); addCurves(this.background, testPath, edgePath); var underPath = this.background.underPath; var translatedUnitSquare = this.displayView.ConvertRectFromView(unitSquare, fromView: this.background); var transformFromShapeToView = CGAffineTransform.MakeTranslation(translatedUnitSquare.Location.X, translatedUnitSquare.Location.Y); underPath.ApplyTransform(transformFromShapeToView); CATransaction.Begin(); CATransaction.DisableActions = (true); if (this.popup != null) { this.shadowLayer.ShadowPath = shadowPath.CGPath; } this.underView.curve = underPath; this.displayView.curve = testPath; this.borderView.curve = edgePath; var borderLayer = this.borderView.Layer as CAShapeLayer; if (borderLayer != null) { borderLayer.StrokeColor = UIColor.Green.CGColor; } CATransaction.Commit(); }
public virtual void updateColors() { CATransaction.Begin(); CATransaction.DisableActions = (true); var switchColors = this.Highlighted || this.Selected; if (switchColors) { if (downColor != null) { this.displayView.fillColor = downColor; } else { this.displayView.fillColor = this.color; } var downUnderColor = this.downUnderColor; if (downUnderColor != null && this.underView != null) { this.underView.fillColor = downUnderColor; } else if (this.underView != null) { this.underView.fillColor = this.underColor; } var downBorderColor = this.downBorderColor; if (downBorderColor != null && this.borderView != null) { this.borderView.strokeColor = downBorderColor; } else if (this.borderView != null) { this.borderView.strokeColor = this.borderColor; } var downTextColor = this.downTextColor; if (downTextColor != null) { this.label.TextColor = downTextColor; if (this.popupLabel != null) { this.popupLabel.TextColor = downTextColor; } if (this.shape != null) { this.shape.color = downTextColor; } } else { this.label.TextColor = this.textColor; if (this.popupLabel != null) { this.popupLabel.TextColor = this.textColor; } if (this.shape != null) { this.shape.color = this.textColor; } } } else { this.displayView.fillColor = this.color; this.displayView.strokeColor = this.color; this.underView.fillColor = this.underColor; this.borderView.strokeColor = this.borderColor; this.label.TextColor = this.textColor; if (this.popupLabel != null) { this.popupLabel.TextColor = this.textColor; } if (this.shape != null) { this.shape.color = this.textColor; } } if (this.popup != null) { this.displayView.fillColor = this.popupColor; } CATransaction.Commit(); }
public override void PushViewController(UIViewController viewController, bool animated) { if (ViewControllers.Length <= 0) { // NOTE: pushViewController is called by init(rootViewController: UIViewController) // so we must perform the normal super method in this case. base.PushViewController(viewController, animated: true); return; } UINavigationController presentingViewController = null; if (PresentingViewController is UINavigationController) { presentingViewController = PresentingViewController as UINavigationController; } else if (PresentingViewController is UITabBarController) { presentingViewController = ((UITabBarController)PresentingViewController).SelectedViewController as UINavigationController; } if (presentingViewController == null) { PresentViewController(viewController, animated, null); System.Diagnostics.Debug.WriteLine("SideMenu Warning: cannot push a ViewController from a ViewController without a NavigationController. It will be presented it instead."); return; } // to avoid overlapping dismiss & pop/push calls, create a transaction block where the menu // is dismissed after showing the appropriate screen CATransaction.Begin(); CATransaction.CompletionBlock = () => { if (SideMenuManager.MenuPushStyle != SideMenuManager.MenuPushStyleType.NoNavigation) { this.DismissViewController(true, null); } this.VisibleViewController?.ViewWillAppear(false); // Hack: force selection to get cleared on UITableViewControllers when reappearing using custom transitions }; UIView.Animate(SideMenuManager.AnimationDismissDuration, animation: () => SideMenuManager.SideMenuTransition.HideMenuStart()); if (!SideMenuManager.AllowPushOfSameClassTwice) { //TODO: Review this var lastView = ViewControllers.LastOrDefault(); if (lastView != null && lastView.GetType() == viewController.GetType()) //if presentingViewController.viewControllers.last?.dynamicType == viewController.dynamicType { { CATransaction.Commit(); return; } } switch (SideMenuManager.MenuPushStyle) { case SideMenuManager.MenuPushStyleType.SubMenu: case SideMenuManager.MenuPushStyleType.DefaultBehavior: break; case SideMenuManager.MenuPushStyleType.PopWhenPossible: foreach (var subViewController in presentingViewController.ViewControllers.Reverse()) { if (subViewController.GetType() == viewController.GetType()) { presentingViewController.PopToViewController(subViewController, animated: animated); CATransaction.Commit(); return; } } break; case SideMenuManager.MenuPushStyleType.Preserve: case SideMenuManager.MenuPushStyleType.PreserveAndHideBackButton: var viewControllers = presentingViewController.ViewControllers; var preservedViewController = viewControllers.Where(x => x.GetType() == viewController.GetType()).LastOrDefault(); if (preservedViewController != null) { if (SideMenuManager.MenuPushStyle == SideMenuManager.MenuPushStyleType.PreserveAndHideBackButton) { preservedViewController.NavigationItem.SetHidesBackButton(true, false); } viewControllers.Append(preservedViewController); presentingViewController.SetViewControllers(viewControllers, animated: animated); CATransaction.Commit(); return; } if (SideMenuManager.MenuPushStyle == SideMenuManager.MenuPushStyleType.PreserveAndHideBackButton) { viewController.NavigationItem.SetHidesBackButton(true, false); } break; case SideMenuManager.MenuPushStyleType.Replace: case SideMenuManager.MenuPushStyleType.NoNavigation: if (SideMenuManager.MenuPushStyle != SideMenuManager.MenuPushStyleType.NoNavigation) { viewController.NavigationItem.LeftBarButtonItem = SideMenuManager.LeftNavigationController.NavigationItem.LeftBarButtonItem; viewController.NavigationItem.RightBarButtonItem = SideMenuManager.LeftNavigationController.NavigationItem.RightBarButtonItem; } else { viewController.NavigationItem.SetHidesBackButton(true, false); } UIViewController[] viewctrl = { viewController }; presentingViewController.SetViewControllers(viewctrl, true); CATransaction.Commit(); return; default: break; } presentingViewController.PushViewController(viewController, animated: animated); CATransaction.Commit(); }
public async void DidOutputMetadataObjects(AVCaptureMetadataOutput captureOutput, AVMetadataObject[] faces, AVCaptureConnection connection) { Console.WriteLine("Got metadata"); try { List <int> unseen = faceViews.Keys.ToList(); List <int> seen = new List <int>(); CATransaction.Flush(); CATransaction.Begin(); CATransaction.SetValueForKey(NSObject.FromObject(true), (NSString)(CATransaction.DisableActions.ToString())); foreach (var face in faces) { // HACK: int faceId = (face as AVMetadataFaceObject).FaceID; int faceId = (int)(face as AVMetadataFaceObject).FaceID; unseen.Remove(faceId); seen.Add(faceId); FaceView view; if (faceViews.ContainsKey(faceId)) { view = faceViews[faceId]; } else { view = new FaceView(); view.Layer.CornerRadius = 10; view.Layer.BorderWidth = 3; view.Layer.BorderColor = UIColor.Green.CGColor; previewView.AddSubview(view); faceViews.Add(faceId, view); view.Id = faceId; view.Callback = TouchCallBack; if (lockedFaceID != null) { view.Alpha = 0; } } AVMetadataFaceObject adjusted = (AVMetadataFaceObject)(previewView.Layer as AVCaptureVideoPreviewLayer).GetTransformedMetadataObject(face); view.Frame = adjusted.Bounds; } foreach (int faceId in unseen) { FaceView view = faceViews[faceId]; view.RemoveFromSuperview(); faceViews.Remove(faceId); if (faceId == lockedFaceID) { clearLockedFace(); } } if (lockedFaceID != null) { FaceView view = faceViews[lockedFaceID.GetValueOrDefault()]; // HACK: Cast resulting nfloat to float // float size = (float)Math.Max (view.Frame.Size.Width, view.Frame.Size.Height) / device.VideoZoomFactor; float size = (float)(Math.Max(view.Frame.Size.Width, view.Frame.Size.Height) / device.VideoZoomFactor); float zoomDelta = lockedFaceSize / size; float lockTime = (float)(CATransition.CurrentMediaTime() - this.lockTime); float zoomRate = (float)(Math.Log(zoomDelta) / lockTime); if (Math.Abs(zoomDelta) > 0.1) { device.RampToVideoZoom(zoomRate > 0 ? MaxZoom : 1, zoomRate); } } } catch { Console.WriteLine("error weird"); } finally { CATransaction.Commit(); } lock (lockerobj) { if (processingFaceDetection) { return; } processingFaceDetection = true; } //CATransaction.Begin(); //CATransaction.SetValueForKey(NSObject.FromObject(true), (NSString)(CATransaction.DisableActions.ToString())); AVCaptureConnection avcaptureconnection = stillImageOutput.ConnectionFromMediaType(AVMediaType.Video); //AVCaptureAutoExposureBracketedStillImageSettings bracketedstillimagesettings = AVCaptureAutoExposureBracketedStillImageSettings.Create(exposureTargetBias: AVCaptureDevice.ExposureTargetBiasCurrent); //var settings = new AVCaptureBracketedStillImageSettings[] { bracketedstillimagesettings }; //stillImageOutput.PrepareToCaptureStillImageBracket(avcaptureconnection,settings, (status,error)=> { // if (error == null) { // stillImageOutput.CaptureStillImageAsynchronously(avcaptureconnection, // (CMSampleBuffer imageDataSampleBuffer, NSError nserror) => { // if (nserror == null) { // using (var sampleBuffer = imageDataSampleBuffer) { // if (sampleBuffer != null) { // using (NSData imageData = AVCaptureStillImageOutput.JpegStillToNSData(sampleBuffer)) { // if (imageData != null) { // uIImage = UIImage.LoadFromData(imageData); // /// operater your image // //Console.WriteLine(image); // SetImage(uIImage); // } // } // } // else { // Console.WriteLine("something was wrong"); // } // } // } // }); // } //}); //CATransaction.Commit(); //DispatchQueue.MainQueue.DispatchAsync(() => { // CaptureImageWithMetadata(stillImageOutput, avcaptureconnection); //}); //stillImageOutput.CaptureStillImageAsynchronously(avcaptureconnection, //(CMSampleBuffer imageDataSampleBuffer, NSError nserror) => { // if (nserror == null) { // //DispatchQueue.GetGlobalQueue(DispatchQueuePriority.Default).DispatchAsync(() => // //{ // DispatchQueue.MainQueue.DispatchAsync(() => { // UIAlertView alert = new UIAlertView(); // alert.Show(); // }); // //}); // //DispatchQueue.MainQueue.DispatchAsync(delegate // //{ // CIImage image = null; // using (var sampleBuffer = imageDataSampleBuffer) { // NSData imageData = AVCaptureStillImageOutput.JpegStillToNSData(sampleBuffer); // image = CIImage.FromData(imageData); // } // uIImage = image.MakeUIImageFromCIImage(); // ivPictureTaken.BackgroundColor = UIColor.Blue; // //ivPictureTaken.Image = uIImage; // //Thread.Sleep(2000); // //processingFaceDetection = false; // //}); // } // else { // Console.WriteLine("Something went wrong"); // } //}); ivPictureTaken.BackgroundColor = (ivPictureTaken.BackgroundColor == UIColor.Blue)? UIColor.Black : UIColor.Blue; await Task.Delay(1000); CMSampleBuffer sampleBuffer = await stillImageOutput.CaptureStillImageTaskAsync(avcaptureconnection); foreach (var face in faces) { int faceId = (int)(face as AVMetadataFaceObject).FaceID; if (faceViews != null && faceViews.ContainsKey(faceId)) { var view = faceViews[faceId]; view.Frame = CGRect.Empty; view.RemoveFromSuperview(); } } teardownAVFoundationFaceDetection(); CIImage ciImage = null; UIImage uIImage = null; UIImage transformeduIImage = null; using (sampleBuffer ) { NSData imageData = AVCaptureStillImageOutput.JpegStillToNSData(sampleBuffer); arregloJPG = imageData.ToArray(); ciImage = CIImage.FromData(imageData); uIImage = new UIImage(imageData); CGAffineTransform cGAffineTransform = new CGAffineTransform(); switch (deviceOrientation) { case UIDeviceOrientation.Portrait: cGAffineTransform = CGAffineTransform.MakeRotation(DegreesToRadians(0)); break; case UIDeviceOrientation.PortraitUpsideDown: cGAffineTransform = (CGAffineTransform.MakeRotation(DegreesToRadians(180))); break; case UIDeviceOrientation.LandscapeLeft: cGAffineTransform = CGAffineTransform.MakeRotation(DegreesToRadians(90)); break; case UIDeviceOrientation.LandscapeRight: cGAffineTransform = CGAffineTransform.MakeRotation(DegreesToRadians(-90)); //cGAffineTransform.Translate(uIImage.CGImage.Width,0); break; case UIDeviceOrientation.FaceUp: case UIDeviceOrientation.FaceDown: default: break; // leave the layer in its last known orientation } var flags = CGBitmapFlags.PremultipliedFirst | CGBitmapFlags.ByteOrder32Little; // Create a CGImage on the RGB colorspace from the configured parameter above using (var cs = CGColorSpace.CreateDeviceRGB()) { using (CGBitmapContext context = new CGBitmapContext(null, (int)uIImage.CGImage.Width, (int)uIImage.CGImage.Height, uIImage.CGImage.BitsPerComponent, uIImage.CGImage.BytesPerRow, cs, (CGImageAlphaInfo)flags)) { context.ConcatCTM(cGAffineTransform); var cgRect = new CGRect(0, 0, uIImage.CGImage.Width, uIImage.CGImage.Height); context.DrawImage(cgRect, uIImage.CGImage); //ciImage = context.ToImage(); using (CGImage cgImage2 = context.ToImage()) { //pixelBuffer.Unlock(CVPixelBufferLock.None); transformeduIImage = UIImage.FromImage(cgImage2); //return UIImage.FromImage(cgImage); } } } } sampleBuffer.Dispose(); //UIImage uIImage = image2.MakeUIImageFromCIImage(); NSData nsdata = uIImage.ResizeImageWithAspectRatio(640, 480).AsPNG(); ivPictureTaken.Image = UIImage.LoadFromData(nsdata);//uIImage; //byte[] bytes = nsdata.ToArray(); //WriteToFile(nsdata); //string encoded = Base64.EncodeToString(localdata, Base64Flags.Default); //byte[] b = System.IO.File.ReadAllBytes(FileName); //string rutaCarpeta = Environment.GetFolderPath(Environment.SpecialFolder.Personal); //string resultado = "FotoLAB12"; //archivoLocal = resultado + ".jpg"; //ruta = Path.Combine(rutaCarpeta, archivoLocal); //File.WriteAllBytes(ruta, arregloJPG); //ivPictureTaken.Image= UIImage.FromFile(ruta); //DispatchQueue.MainQueue.DispatchAsync(() => { //ivPictureTaken.Image = null; //InvokeOnMainThread(() => { // ivPictureTaken.BackgroundColor = UIColor.Black; // ivPictureTaken = new UIImageView(uIImage); //}); //ivPictureTaken.SetNeedsDisplay(); //CATransaction.Commit(); //}); //DispatchQueue.GetGlobalQueue(DispatchQueuePriority.Default).DispatchAsync(() => //{ ProcessingImage(nsdata); //}); //DispatchQueue.GetGlobalQueue(DispatchQueuePriority.Default).DispatchAsync(() => { // //NSNotificationCenter.DefaultCenter.PostNotificationName("OnFaceDetected", uIImage); //}); //session.StopRunning(); //await Task.Delay(3000); //processingFaceDetection = false; var a = -1; }
/// <summary> /// Touchs up inside animation. /// </summary> public void TouchUpInsideAnimation() { this.IsPerformingTouchUpInsideAnimation = true; foreach (UIImageView Icon in IconArray) { UIView.AnimateNotify(0.1f, 0.0f, UIViewAnimationOptions.BeginFromCurrentState, () => { Icon.Alpha = 0.0f; }, (finished) => { if (finished) { Icon.Hidden = true; } }); } var BackgroundViewScaleSmallCABasicAnimation = CABasicAnimation.FromKeyPath(@"transform.scale"); BackgroundViewScaleSmallCABasicAnimation.Duration = 0.1f; BackgroundViewScaleSmallCABasicAnimation.AutoReverses = false; BackgroundViewScaleSmallCABasicAnimation.To = NSNumber.FromDouble(SmallPara); BackgroundViewScaleSmallCABasicAnimation.From = NSNumber.FromDouble(MidiumPara); BackgroundViewScaleSmallCABasicAnimation.FillMode = CAFillMode.Forwards; BackgroundViewScaleSmallCABasicAnimation.RemovedOnCompletion = false; BackgroundViewScaleSmallCABasicAnimation.BeginTime = 0.0f; BackgroundView.Layer.AddAnimation(BackgroundViewScaleSmallCABasicAnimation, @"BackgroundViewScaleSmallCABasicAnimation"); var ButtonScaleFullCABasicAnimation = CABasicAnimation.FromKeyPath(@"transform.scale"); ButtonScaleFullCABasicAnimation.Duration = 0.2f; ButtonScaleFullCABasicAnimation.AutoReverses = false; ButtonScaleFullCABasicAnimation.To = NSNumber.FromNFloat(FullPara); ButtonScaleFullCABasicAnimation.From = NSNumber.FromDouble(MidiumPara); ButtonScaleFullCABasicAnimation.FillMode = CAFillMode.Forwards; ButtonScaleFullCABasicAnimation.RemovedOnCompletion = false; ButtonScaleFullCABasicAnimation.BeginTime = 0.0f; var animGroup = CAAnimationGroup.CreateAnimation(); animGroup.Animations = new CAAnimation[] { ButtonScaleFullCABasicAnimation }; animGroup.Duration = 0.4f; animGroup.RemovedOnCompletion = false; animGroup.AutoReverses = false; animGroup.FillMode = CAFillMode.Forwards; CATransaction.Begin(); CATransaction.CompletionBlock = () => { IsPerformingTouchUpInsideAnimation = false; }; SmallButton.Layer.AddAnimation(animGroup, @"ButtonScaleAnimation"); CATransaction.Commit(); CATransform3D Rotate = CATransform3D.MakeRotation(0, 0, 1, 0).Concat(CATransform3D.MakeRotation(0, 1, 0, 0)); if (Parallex) { SmallButton.Layer.Transform = CATransform3DPerspect(Rotate, new CGPoint(0, 0), BigRadius + ParallexParameter); } else { //Do nothing ^_^ } }
public void Toggle() { TitleLabel.Alpha = 0; SizeF size; if (!string.IsNullOrEmpty(_disabled)) { SetTitle(_disabled, UIControlState.Normal);; SetTitleColor(UIColor.FromWhiteAlpha(0.6f, 1.0f), UIControlState.Normal); SetTitleShadowColor(UIColor.FromWhiteAlpha(1.0f, 1.0f), UIControlState.Normal); TitleLabel.ShadowOffset = new SizeF(0.0f, 1.0f); size = TitleLabel.StringSize(_disabled, UIFont.BoldSystemFontOfSize(FontSize)); } else if (!string.IsNullOrEmpty(_confirm) && Selected) { SetTitle(_confirm, UIControlState.Normal); size = TitleLabel.StringSize(_confirm, UIFont.BoldSystemFontOfSize(FontSize)); } else { SetTitle(_title, UIControlState.Normal); size = TitleLabel.StringSize(_title, UIFont.BoldSystemFontOfSize(FontSize)); } size.Width += Padding; float offset = size.Width - Frame.Size.Width; CATransaction.Begin(); CATransaction.AnimationDuration = 0.25f; CATransaction.CompletionBlock = () => { // Re-adjust button frame for new touch area, move layers back now that animation is done var frameRect = new RectangleF(Frame.X - offset, Frame.Y, Frame.Size.Width + offset, Frame.Size.Height); Frame = frameRect; CATransaction.DisableActions = true; foreach (var layer in Layer.Sublayers) { layer.Frame = new RectangleF(layer.Frame.X + offset, layer.Frame.Y, layer.Frame.Size.Width, layer.Frame.Size.Height); } CATransaction.Commit(); TitleLabel.Alpha = 1; SetNeedsLayout(); }; UIColor greenColor = new UIColor(0.439f, 0.741f, 0.314f, 1.0f); // Animate color change var colorAnimation = CABasicAnimation.FromKeyPath(@"backgroundColor"); colorAnimation.RemovedOnCompletion = false; colorAnimation.FillMode = CAFillMode.Forwards; // http://stackoverflow.com/questions/5821181/how-do-i-convert-a-cgcolor-into-an-nsobject-when-using-monotouch if (!string.IsNullOrEmpty(_disabled)) { colorAnimation.From = Runtime.GetNSObject(greenColor.CGColor.Handle); colorAnimation.To = Runtime.GetNSObject(UIColor.FromWhiteAlpha(0.85f, 1.0f).CGColor.Handle); } else { colorAnimation.From = Selected ? Runtime.GetNSObject(_tint.CGColor.Handle) : Runtime.GetNSObject(greenColor.CGColor.Handle); colorAnimation.To = Selected ? Runtime.GetNSObject(greenColor.CGColor.Handle) : Runtime.GetNSObject(_tint.CGColor.Handle); } _colorLayer.AddAnimation(colorAnimation, @"colorAnimation"); // Animate layer scaling foreach (var layer in this.Layer.Sublayers) { layer.Frame = new RectangleF(layer.Frame.X - offset, layer.Frame.Y, layer.Frame.Size.Width + offset, layer.Frame.Size.Height); } CATransaction.Commit(); this.SetNeedsDisplay(); }
void StartInkAtPoint(CGPoint point, bool animated) { nfloat radius = FinalRadius; if (MaxRippleRadius > 0) { radius = MaxRippleRadius; } CGRect ovalRect = new CGRect(Bounds.Width / 2 - radius, Bounds.Height / 2 - radius, radius * 2, radius * 2); UIBezierPath circlePath = UIBezierPath.FromOval(ovalRect); Path = circlePath.CGPath; FillColor = InkColor.CGColor; if (!animated) { Opacity = 1; Position = new CGPoint(Bounds.Width / 2, Bounds.Height / 2); } else { Opacity = 0; Position = point; _startAnimationActive = true; CAMediaTimingFunction materialTimingFunction = CAMediaTimingFunction.FromControlPoints(0.4f, 0, 0.2f, 1.0f); nfloat scaleStart = (nfloat)(Math.Min(Bounds.Width, Bounds.Height) / MDCInkLayerScaleDivisor); if (scaleStart < MDCInkLayerScaleStartMin) { scaleStart = MDCInkLayerScaleStartMin; } else if (scaleStart > MDCInkLayerScaleStartMax) { scaleStart = MDCInkLayerScaleStartMax; } CABasicAnimation scaleAnim = new CABasicAnimation { KeyPath = MDCInkLayerScaleString, From = new NSNumber(scaleStart), To = new NSNumber(1.0f), Duration = MDCInkLayerStartScalePositionDuration, BeginTime = MDCInkLayerCommonDuration, TimingFunction = materialTimingFunction, FillMode = CAFillMode.Forwards, RemovedOnCompletion = true }; UIBezierPath centerPath = new UIBezierPath(); CGPoint startPoint = point; CGPoint endPoint = new CGPoint(Bounds.Width / 2, Bounds.Height / 2); centerPath.MoveTo(startPoint); centerPath.AddLineTo(endPoint); centerPath.ClosePath(); CAKeyFrameAnimation positionAnim = new CAKeyFrameAnimation { KeyPath = MDCInkLayerPositionString, Path = centerPath.CGPath, KeyTimes = new NSNumber[] { 0, 1.0f }, Values = new NSNumber[] { 0, 1.0f }, Duration = MDCInkLayerStartScalePositionDuration, BeginTime = MDCInkLayerCommonDuration, TimingFunction = materialTimingFunction, FillMode = CAFillMode.Forwards, RemovedOnCompletion = false }; CABasicAnimation fadeInAnim = new CABasicAnimation(); fadeInAnim.KeyPath = MDCInkLayerOpacityString; fadeInAnim.From = new NSNumber(0); fadeInAnim.To = new NSNumber(1.0f); fadeInAnim.Duration = MDCInkLayerCommonDuration; fadeInAnim.BeginTime = MDCInkLayerCommonDuration; fadeInAnim.TimingFunction = CAMediaTimingFunction.FromName(CAMediaTimingFunction.Linear); fadeInAnim.FillMode = CAFillMode.Forwards; fadeInAnim.RemovedOnCompletion = false; CATransaction.Begin(); CAAnimationGroup animGroup = new CAAnimationGroup(); animGroup.Animations = new CAAnimation[] { scaleAnim, positionAnim, fadeInAnim }; animGroup.Duration = MDCInkLayerStartScalePositionDuration; animGroup.FillMode = CAFillMode.Forwards; animGroup.RemovedOnCompletion = false; CATransaction.CompletionBlock = new Action(() => { _startAnimationActive = false; }); AddAnimation(animGroup, null); CATransaction.Commit(); } //if (AnimationDelegate respondsToSelector: @selector(inkLayerAnimationDidStart:)) //{ // [self.animationDelegate inkLayerAnimationDidStart:self]; //} }
void drawFaces(CIFeature[] features, CGRect clearAperture, UIDeviceOrientation orientation) { var sublayers = this.previewLayer.Sublayers; int sublayersCount = sublayers.Length, currentSublayer = 0; int featuresCount = features.Length, currentFeature = 0; CATransaction.Begin(); CATransaction.DisableActions = true; //CATransaction.SetValueForKey (true, CATransaction.DisableActionsKey); // hide all the face layers foreach (CALayer layer in sublayers) { if (layer.Name == "FaceLayer") { layer.Hidden = true; } } if (featuresCount == 0) { CATransaction.Commit(); return; // early bail. } var parentFrameSize = this.previewView.Frame.Size; var gravity = this.previewLayer.VideoGravity; var isMirrored = this.previewLayer.Mirrored; CGRect previewBox = videoPreviewBoxForGravity( gravity, parentFrameSize, clearAperture.Size ); foreach (CIFaceFeature ff 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 = ff.Bounds; // flip preview width and height var temp = faceRect.Size.Width; faceRect.Width = faceRect.Size.Height; faceRect.Height = temp; temp = faceRect.Location.X; faceRect.X = faceRect.Location.Y; faceRect.Y = temp; // 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; faceRect.Width *= widthScaleBy; faceRect.Height *= heightScaleBy; faceRect.X *= widthScaleBy; faceRect.Y *= heightScaleBy; if (isMirrored) { /*faceRect = */ faceRect.Offset(previewBox.Location.X + previewBox.Size.Width - faceRect.Size.Width - (faceRect.Location.X * 2), previewBox.Location.Y); } else { /*faceRect = */ faceRect.Offset(previewBox.Location.X, previewBox.Location.Y); } CALayer featureLayer = null; // re-use an existing layer if possible while (featureLayer == null && (currentSublayer < sublayersCount)) { var currentLayer = sublayers [currentSublayer++]; if (currentLayer.Name == "FaceLayer") { featureLayer = currentLayer; currentLayer.Hidden = false; } } // create a new one if necessary if (featureLayer == null) { featureLayer = new CALayer(); featureLayer.Contents = this.borderImage.CGImage; featureLayer.Name = "FaceLayer"; this.previewLayer.AddSublayer(featureLayer); featureLayer = null; } featureLayer.Frame = faceRect; switch (orientation) { 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(); }
public void Flip(FlipDirection direction, NSAction completion) { if (flippingInProgress || FrontView == null || BackView == null) { return; } flippingInProgress = true; projectionLayer = CALayer.Create(); // this is to make the perspective and 2.5D effect projectionLayer.Frame = this.Layer.Bounds; var perspective = CATransform3D.Identity; float zDistanse = 350f; // change this to the actual perspective and distance of the projection plane perspective.m34 = 1f / -zDistanse; projectionLayer.SublayerTransform = perspective; this.Layer.AddSublayer(projectionLayer); frontImage = FrontView.GetImage(); backImage = BackView.GetImage(); topFaceLayer = new GradientLayer(GradientLayerType.Face, GradientLayerAreaType.Top); topFaceLayer.Frame = new RectangleF(0f, 0f, projectionLayer.Frame.Size.Width, (float)Math.Floor(projectionLayer.Frame.Size.Height / 2f)); bottomFaceLayer = new GradientLayer(GradientLayerType.Face, GradientLayerAreaType.Bottom); bottomFaceLayer.Frame = new RectangleF(0f, (float)Math.Floor(projectionLayer.Frame.Size.Height / 2f), projectionLayer.Frame.Size.Width, (float)Math.Floor(projectionLayer.Frame.Size.Height / 2f)); mainFlipLayer = new DoubleSidedLayer(); mainFlipLayer.AnchorPoint = new PointF(1f, 1f); mainFlipLayer.Frame = new RectangleF(0f, 0f, projectionLayer.Frame.Size.Width, (float)Math.Floor(projectionLayer.Frame.Size.Height / 2f)); mainFlipLayer.ZPosition = 1f; mainFlipLayer.FrontLayer = new GradientLayer(GradientLayerType.Flip, GradientLayerAreaType.Top); mainFlipLayer.BackLayer = new GradientLayer(GradientLayerType.Flip, GradientLayerAreaType.Bottom); // offscreen rendering optimization to reuse the offscreen buffer topFaceLayer.ShouldRasterize = true; bottomFaceLayer.ShouldRasterize = true; if (direction == FlipDirection.Down) { topFaceLayer.Contents = backImage.CGImage; bottomFaceLayer.Contents = frontImage.CGImage; mainFlipLayer.FrontLayer.Contents = frontImage.CGImage; mainFlipLayer.BackLayer.Contents = backImage.CGImage; topFaceLayer.GradientOpacity = 1f; mainFlipLayer.Transform = CATransform3D.Identity; } else { topFaceLayer.Contents = frontImage.CGImage; bottomFaceLayer.Contents = backImage.CGImage; mainFlipLayer.FrontLayer.Contents = backImage.CGImage; mainFlipLayer.BackLayer.Contents = frontImage.CGImage; bottomFaceLayer.GradientOpacity = 1f; mainFlipLayer.Transform = CATransform3D.MakeRotation((float)-Math.PI, 1f, 0f, 0f); } // Add layers to the projection layer, so we apply the projections to it projectionLayer.AddSublayer(topFaceLayer); projectionLayer.AddSublayer(bottomFaceLayer); projectionLayer.AddSublayer(mainFlipLayer); NSTimer.CreateScheduledTimer(0.01, delegate { CATransaction.Begin(); CATransaction.AnimationDuration = Duration; CATransaction.AnimationTimingFunction = CAMediaTimingFunction.FromName(CAMediaTimingFunction.EaseOut); CATransaction.CompletionBlock = delegate { fv = this.FrontView; FrontView = BackView; BackView = fv; flippingInProgress = false; if (completion != null) { completion.Invoke(); } }; // this is the whole trick, change the angle in timing function float angle = (float)Math.PI * (1f - (float)direction); mainFlipLayer.Transform = CATransform3D.MakeRotation(angle, 1f, 0f, 0f); topFaceLayer.GradientOpacity = (float)direction; bottomFaceLayer.GradientOpacity = 1f - (float)direction; mainFlipLayer.FrontLayer.GradientOpacity = 1f - (float)direction; mainFlipLayer.BackLayer.GradientOpacity = (float)direction; CATransaction.Commit(); }); }
protected void Exit(bool animated, Action completionBlock) { base.Exit(animated); if (!animated) { RemoveAllAnimations(); CATransaction.Begin(); CATransaction.DisableActions = true; Opacity = 0; //__weak MDCLegacyInkLayerForegroundRipple * weakSelf = self; CATransaction.CompletionBlock = new Action(() => { this.RemoveFromSuperLayer(); if (this.animationDelegate != null) { animationDelegate.AnimationDidStop(null, this, true); } }); CATransaction.Commit(); return; } if (Bounded) { ForegroundOpacityAnim.Values = new NSNumber[] { 1, 0 }; ForegroundOpacityAnim.Duration = kInkLayerForegroundBoundedOpacityExitDuration; // Bounded ripples move slightly towards the center of the tap target. Unbounded ripples // move to the center of the tap target. nfloat xOffset = (nfloat)(TargetFrame.X - InkLayer?.Frame.X); nfloat yOffset = (nfloat)(TargetFrame.Y - InkLayer?.Frame.Y); CGPoint startPoint = new CGPoint(Point.X + xOffset, Point.Y + yOffset); CGPoint endPoint = MDCLegacyInkLayerRectGetCenter(TargetFrame); if (UseCustomInkCenter) { endPoint = new CGPoint(CustomInkCenter, CustomInkCenter); } endPoint = new CGPoint(endPoint.X + xOffset, endPoint.Y + yOffset); CGPoint centerOffsetPoint = MDCLegacyInkLayerInterpolatePoint(startPoint, endPoint, 0.3f); UIBezierPath movePath = new UIBezierPath(); movePath.MoveTo(startPoint); movePath.AddLineTo(centerOffsetPoint); ForegroundPositionAnim = PositionAnimWithPath(movePath.CGPath, duration: kInkLayerForegroundBoundedPositionExitDuration, timingFunction: LogDecelerateEasing()); ForegroundScaleAnim.Values = new NSNumber[] { 0, 1 }; ForegroundScaleAnim.KeyTimes = new NSNumber[] { 0, 1 }; ForegroundScaleAnim.Duration = kInkLayerForegroundBoundedRadiusExitDuration; } else { NSNumber opacityVal = (NSNumber)PresentationLayer.ValueForKey((NSString)kInkLayerOpacity); if (opacityVal == null) { opacityVal = NSNumber.FromFloat(0.0f); } nfloat adjustedDuration = kInkLayerForegroundBoundedPositionExitDuration; nfloat normOpacityVal = opacityVal.FloatValue; nfloat opacityDuration = normOpacityVal / 3.0f; ForegroundOpacityAnim.Values = new NSNumber[] { opacityVal, 0 }; ForegroundOpacityAnim.Duration = opacityDuration + adjustedDuration; NSNumber scaleVal = (NSNumber)PresentationLayer.ValueForKey((NSString)kInkLayerScale); if (scaleVal == null) { scaleVal = NSNumber.FromFloat(0.0f); } nfloat unboundedDuration = (nfloat)Math.Sqrt(((1.0f - scaleVal.FloatValue) * Radius) / (kInkLayerForegroundWaveTouchDownAcceleration + kInkLayerForegroundWaveTouchUpAcceleration)); ForegroundPositionAnim.Duration = unboundedDuration + adjustedDuration; ForegroundScaleAnim.Values = new NSNumber[] { scaleVal, 1 }; ForegroundScaleAnim.Duration = unboundedDuration + adjustedDuration; } ForegroundOpacityAnim.KeyTimes = new NSNumber[] { 0, 1 }; if (ForegroundOpacityAnim.Duration < ForegroundScaleAnim.Duration) { ForegroundScaleAnim.Delegate = this; } else { ForegroundOpacityAnim.Delegate = this; } ForegroundOpacityAnim.TimingFunction = CAMediaTimingFunction.FromName(CAMediaTimingFunction.Linear); ForegroundPositionAnim.TimingFunction = LogDecelerateEasing(); ForegroundScaleAnim.TimingFunction = LogDecelerateEasing(); CATransaction.Begin(); if (completionBlock != null) { CATransaction.CompletionBlock = new Action(() => { if (RippleState != MDCInkRippleState.kInkRippleCancelled) { completionBlock(); } }); } AddAnimation(ForegroundOpacityAnim, kInkLayerForegroundOpacityAnim); AddAnimation(ForegroundPositionAnim, kInkLayerForegroundPositionAnim); AddAnimation(ForegroundScaleAnim, kInkLayerForegroundScaleAnim); CATransaction.Commit(); }
// Drawing method void RenderPath(CGContext graphics, CGRect bounds) { if (basicPath == null) { return; } if (stroke == null && fill == null) { return; } // Disable animations. CATransaction.Begin(); CATransaction.DisableActions = true; // If it's a Rectangle, RadiusX and RadiusY must be independent of Stretch if (view is RectangleUIView) { // BoundingBox is the same as PathBoundingBox for Rectangle but probably cheaper CGRect renderPathBounds = renderPath.BoundingBox; nfloat radiusX = (view as RectangleUIView).RadiusX; nfloat radiusY = (view as RectangleUIView).RadiusY; renderPath = new CGPath(); renderPath.AddRoundedRect(renderPathBounds, radiusX, radiusY); } // Set various graphics attributes for stroking graphics.SetLineWidth(strokeWidth); graphics.SetLineDash(dashPhase * strokeWidth, dashLengths); graphics.SetLineCap(strokeLineCap); graphics.SetLineJoin(strokeLineJoin); graphics.SetMiterLimit(strokeMiterLimit * strokeWidth / 4); // TODO: Check if this is right if (stroke is CGColor && fill is CGColor) { graphics.AddPath(renderPath); graphics.SetStrokeColor((CGColor)stroke); graphics.SetFillColor((CGColor)fill); graphics.DrawPath(isNonzeroFill ? CGPathDrawingMode.FillStroke : CGPathDrawingMode.EOFillStroke); } else { if (fill is CGColor) { graphics.AddPath(renderPath); graphics.SetFillColor((CGColor)fill); graphics.DrawPath(isNonzeroFill ? CGPathDrawingMode.Fill : CGPathDrawingMode.EOFill); } else if (fill != null) { graphics.AddPath(renderPath); if (fill is LinearGradientBrush) { if (isNonzeroFill) { graphics.Clip(); } else { graphics.EOClip(); } // Fill the area with a gradient RenderLinearGradient(graphics, renderPathBounds, fill as LinearGradientBrush); } else if (fill is ImageBrush) { RenderImageBrush(graphics, fill as ImageBrush, true); } } if (stroke is CGColor) { graphics.AddPath(renderPath); graphics.SetStrokeColor((CGColor)stroke); graphics.DrawPath(CGPathDrawingMode.Stroke); } else if (stroke != null) { graphics.AddPath(renderPath); if (stroke is LinearGradientBrush) { graphics.ReplacePathWithStrokedPath(); graphics.Clip(); // Stroke with a gradient RenderLinearGradient(graphics, renderPathStrokeBounds, stroke as LinearGradientBrush); } else if (stroke is ImageBrush) { RenderImageBrush(graphics, stroke as ImageBrush, false); } } } CATransaction.Commit(); }
public override void PushViewController(UIViewController viewController, bool animated) { if (ViewControllers.Length <= 0) { // NOTE: pushViewController is called by init(rootViewController: UIViewController) // so we must perform the normal super method in this case. base.PushViewController(viewController, animated: true); return; } UINavigationController presentingViewController = null; if (PresentingViewController is UINavigationController) { presentingViewController = PresentingViewController as UINavigationController; } else if (PresentingViewController is UITabBarController) { presentingViewController = ((UITabBarController)PresentingViewController).SelectedViewController as UINavigationController; } if (presentingViewController == null) { PresentViewController(viewController, animated, null); System.Diagnostics.Debug.WriteLine("SideMenu Warning: cannot push a ViewController from a ViewController without a NavigationController. It will be presented it instead."); return; } // to avoid overlapping dismiss & pop/push calls, create a transaction block where the menu // is dismissed after showing the appropriate screen CATransaction.Begin(); CATransaction.CompletionBlock = () => { this.DismissViewController(true, null); this.VisibleViewController?.ViewWillAppear(false); // Hack: force selection to get cleared on UITableViewControllers when reappearing using custom transitions }; UIView.Animate(SideMenuManager.AnimationDismissDuration, animation: () => SideMenuManager.SideMenuTransition.HideMenuStart()); if (SideMenuManager.AllowPopIfPossible) { foreach (var subViewController in presentingViewController.ViewControllers) { //TODO: Review this if (subViewController.GetType() == viewController.GetType()) // if subViewController.dynamicType == viewController.dynamicType { { presentingViewController.PopToViewController(subViewController, animated: animated); CATransaction.Commit(); return; } } } if (!SideMenuManager.AllowPushOfSameClassTwice) { //TODO: Review this if (presentingViewController.ViewControllers[presentingViewController.ViewControllers.Length - 1].GetType() == viewController.GetType()) //if presentingViewController.viewControllers.last?.dynamicType == viewController.dynamicType { { CATransaction.Commit(); return; } } presentingViewController.PushViewController(viewController, animated: animated); CATransaction.Commit(); }
// Called by above and when Stretch and render-size changes. void BuildRenderPath() { if (basicPath == null) { renderPath = null; renderPathBounds = new CGRect(); renderPathStrokeBounds = new CGRect(); return; } // Disable animations. CATransaction.Begin(); CATransaction.DisableActions = true; if (stretch != Stretch.None) { // Adjust for Stretch setting CGRect viewBounds = Bounds; viewBounds.X += strokeWidth / 2; viewBounds.Y += strokeWidth / 2; viewBounds.Width -= strokeWidth; viewBounds.Height -= strokeWidth; // Compare with path geometry only (i.e., basicPathBounds rather than basicPathStrokeBounds) nfloat widthScale = viewBounds.Width / basicPathBounds.Width; nfloat heightScale = viewBounds.Height / basicPathBounds.Height; CGAffineTransform stretchTransform = CGAffineTransform.MakeIdentity(); switch (stretch) { case Stretch.None: break; case Stretch.Fill: stretchTransform.Scale(widthScale, heightScale); stretchTransform.Translate(viewBounds.Left - widthScale * basicPathBounds.Left, viewBounds.Top - heightScale * basicPathBounds.Top); break; case Stretch.Uniform: nfloat minScale = NMath.Min(widthScale, heightScale); stretchTransform.Scale(minScale, minScale); stretchTransform.Translate(viewBounds.Left - minScale * basicPathBounds.Left + // scale and position (viewBounds.Width - minScale * basicPathBounds.Width) / 2, // and center horizontally viewBounds.Top - minScale * basicPathBounds.Top + // scale and position (viewBounds.Height - minScale * basicPathBounds.Height) / 2); // and center vertically break; case Stretch.UniformToFill: nfloat maxScale = NMath.Max(widthScale, heightScale); stretchTransform.Scale(maxScale, maxScale); stretchTransform.Translate(viewBounds.Left - maxScale * basicPathBounds.Left, viewBounds.Top - maxScale * basicPathBounds.Top); break; } Frame = Bounds; renderPath = basicPath.CopyByTransformingPath(stretchTransform); } else { // Adjust non-stretched paths for negative coordinates. nfloat adjustX = NMath.Min(0, basicPathStrokeBounds.X); nfloat adjustY = NMath.Min(0, basicPathStrokeBounds.Y); if (adjustX < 0 || adjustY < 0) { nfloat width = Bounds.Width; nfloat height = Bounds.Height; if (basicPathStrokeBounds.Width > Bounds.Width) { width = Bounds.Width - adjustX; } if (basicPathStrokeBounds.Height > Bounds.Height) { height = Bounds.Height - adjustY; } Frame = new CGRect(adjustX, adjustY, width, height); CGAffineTransform xform = new CGAffineTransform(Bounds.Width / width, 0, 0, Bounds.Height / height, -adjustX, -adjustY); renderPath = basicPath.CopyByTransformingPath(xform); } else { Frame = Bounds; renderPath = basicPath.CopyByTransformingPath(CGAffineTransform.MakeIdentity()); } } renderPathBounds = renderPath.PathBoundingBox; renderPathStrokeBounds = renderPath.CopyByStrokingPath(strokeWidth, strokeLineCap, strokeLineJoin, strokeMiterLimit).PathBoundingBox; CATransaction.Commit(); SetNeedsDisplay(); }
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(); }
public override void UpdateLayer() { base.UpdateLayer(); if (image != null && imageLayer == null) { Layer.MasksToBounds = false; if (maskLayer == null) { maskLayer = CAShapeLayer.Create() as CAShapeLayer; Layer.AddSublayer(maskLayer); maskLayer.Path = CGPath.FromRoundedRect(Bounds, cornerRadius, cornerRadius); } imageLayer = CALayer.Create(); imageLayer.Mask = maskLayer; imageLayer.MasksToBounds = true; image.LockFocus(); imageLayer.Contents = image.CGImage; imageLayer.ContentsGravity = CALayer.GravityResizeAspectFill; image.UnlockFocus(); Layer.AddSublayer(imageLayer); } if (image == null) { imageLayer?.RemoveFromSuperLayer(); } if (overlayAlpha > 0 && overlayLayer == null) { overlayLayer = new CALayer(); overlayLayer.BackgroundColor = overlayColor.ColorWithAlphaComponent(overlayAlpha).CGColor; Layer.AddSublayer(overlayLayer); } if (overlayAlpha == 0 && overlayLayer != null) { overlayLayer.RemoveFromSuperLayer(); overlayLayer = null; } CATransaction.Begin(); CATransaction.DisableActions = true; if (imageLayer != null) { if (imageLayer.Bounds.Width != Bounds.Width) { imageLayer.Frame = Bounds; maskLayer.Path = CGPath.FromRoundedRect(Bounds, cornerRadius, cornerRadius); } } if (overlayLayer != null && overlayLayer.SuperLayer != null && overlayLayer.Frame != Bounds) { overlayLayer.Frame = Bounds; } CATransaction.Commit(); }
private void SetSelectedSegmentIndex(int index, bool animated = false, bool notify = false) { SelectedIndex = index; SetNeedsDisplay(); if (index == -1) { SelectionIndicatorArrowLayer.RemoveFromSuperLayer(); SelectionIndicatorStripLayer.RemoveFromSuperLayer(); SelectionIndicatorBoxLayer.RemoveFromSuperLayer(); } else { ScrollToSelectedSegmentIndex(animated); if (animated) { if (SelectionStyle == HMSegmentedControlSelectionStyle.Arrow) { AddScrollViewSubLayer(SelectionIndicatorArrowLayer); SetSelectedSegmentIndex(index, false, true); return; } else { if (SelectionIndicatorStripLayer.SuperLayer == null) { AddScrollViewSubLayer(SelectionIndicatorStripLayer); if (SelectionStyle == HMSegmentedControlSelectionStyle.Box && SelectionIndicatorBoxLayer.SuperLayer == null) { InsertScrollViewSubLayer(SelectionIndicatorBoxLayer, 0); } SetSelectedSegmentIndex(index, false, true); } } if (notify) { NotifyForSegmentChange(index); } SelectionIndicatorArrowLayer.Actions = new NSDictionary(); SelectionIndicatorStripLayer.Actions = new NSDictionary(); SelectionIndicatorBoxLayer.Actions = new NSDictionary(); CATransaction.Begin(); CATransaction.AnimationDuration = 0.15f; CATransaction.AnimationTimingFunction = CAMediaTimingFunction.FromName(CAMediaTimingFunction.Linear); SetArrowFrame(); SelectionIndicatorBoxLayer.Frame = FrameForSelectionIndicator(); SelectionIndicatorStripLayer.Frame = FrameForSelectionIndicator(); SelectionIndicatorBoxLayer.Frame = FrameForFillerSelectionIndicator(); CATransaction.Commit(); } else { var newActions = new NSMutableDictionary(); newActions.Add(new NSString("position"), NSNull.Null); newActions.Add(new NSString("bounds"), NSNull.Null); SelectionIndicatorArrowLayer.Actions = newActions; SelectionIndicatorStripLayer.Actions = newActions; SelectionIndicatorBoxLayer.Actions = newActions; SelectionIndicatorStripLayer.Frame = FrameForSelectionIndicator(); SelectionIndicatorBoxLayer.Frame = FrameForFillerSelectionIndicator(); if (notify) { NotifyForSegmentChange(index); } } } }
public void SetMagnitudes(double [] magnitudeData) { if (curveLayer == null) { curveLayer = new CAShapeLayer(); curveLayer.FillColor = UIColor.FromRGBA(0.31f, 0.37f, 0.73f, 0.8f).CGColor; graphLayer.AddSublayer(curveLayer); } var bezierPath = new CGPath(); var width = graphLayer.Bounds.Width; bezierPath.MoveToPoint(leftMargin, graphLayer.Frame.Height + bottomMargin); float lastDbPos = 0f; float location = leftMargin; var frequencyCount = frequencies?.Count ?? 0; var pixelRatio = (int)(Math.Ceiling(width / frequencyCount)); for (int i = 0; i < frequencyCount; i++) { var dbValue = 20 * Math.Log10(magnitudeData [i]); float dbPos; if (dbValue < -defaultGain) { dbPos = GetLocationForDbValue(-defaultGain); } else if (dbValue > defaultGain) { dbPos = GetLocationForDbValue(defaultGain); } else { dbPos = GetLocationForDbValue((float)dbValue); } if (Math.Abs(lastDbPos - dbPos) >= 0.1) { bezierPath.AddLineToPoint(location, dbPos); } lastDbPos = dbPos; location += pixelRatio; if (location > width + graphLayer.Frame.X) { location = (float)width + (float)graphLayer.Frame.X; break; } } bezierPath.AddLineToPoint(location, graphLayer.Frame.Y + graphLayer.Frame.Height + bottomMargin); bezierPath.CloseSubpath(); CATransaction.Begin(); CATransaction.DisableActions = true; curveLayer.Path = bezierPath; CATransaction.Commit(); UpdateControls(true); }