private void DrawGradientInContext(CGRect rect) { //// General Declarations var colorSpace = CGColorSpace.CreateDeviceRGB(); var context = UIGraphics.GetCurrentContext(); //// Color Declarations var colorGradientEasyToHardColor = UIColor.FromRGBA(0.19f, 0.58f, 0.17f, 1.0f); var colorGradientEasyToHardColor2 = UIColor.FromRGBA(0.8f, 0.0f, 0.0f, 0.78f); //// Gradient Declarations var colorGradientEasyToHardColors = new CGColor [] { colorGradientEasyToHardColor.CGColor, UIColor.FromRGBA(0.5f, 0.3f, 0.09f, 0.9f).CGColor, colorGradientEasyToHardColor2.CGColor }; var colorGradientEasyToHardLocations = new nfloat [] { 0.0f, 0.67f, 1.0f }; var colorGradientEasyToHard = new CGGradient(colorSpace, colorGradientEasyToHardColors, colorGradientEasyToHardLocations); //// Rectangle Drawing var rectanglePath = UIBezierPath.FromRect(rect); context.SaveState(); rectanglePath.AddClip(); context.DrawLinearGradient(colorGradientEasyToHard, new CGPoint(0.0f, (rect.Width / 2)), new CGPoint(rect.Width, (rect.Width / 2)), 0); //context.DrawLinearGradient (colorGradientEasyToHard, new PointF (0.0f, 60.0f), new PointF (240.0f, 60.0f), 0); context.RestoreState(); //// Text Drawing CGRect textRect = new CGRect(rect.X, rect.Y, rect.Width, rect.Height); this.TextColor.SetFill(); textRect.Offset(0.0f, (textRect.Height - new NSString(this.Text).StringSize(this.Font, textRect.Size).Height) / 2.0f); new NSString(this.Text).DrawString(textRect, this.Font, UILineBreakMode.TailTruncation, UITextAlignment.Center); }
UIView CreateSwatchView(ColorRGB color, ColorSchemeType type, string title) { var labelHeight = 20d; var scheme = ColorScheme.CreateColorScheme(color, type); var rowRect = new CGRect(0, labelHeight, swatchSize, swatchSize); var colorView = new UIView() { Frame = new CGRect(0, 0, scheme.Colors.Count * swatchSize, swatchSize + labelHeight) }; var label = new UILabel { Text = title, Font = UIFont.SystemFontOfSize(8f), TextAlignment = UITextAlignment.Center, Frame = new CGRect(0, 0, colorView.Frame.Width, labelHeight) }; colorView.Add(label); for (int i = 0; i < scheme.Colors.Count; i++) { if (i > 0) { rowRect.Offset(swatchSize, 0); } var colorRgb = (ColorRGB)scheme.Colors.Values.ElementAt(i); var swatch = new ColorSwatchView(rowRect, colorRgb, colorRgb.ToHex()); colorView.Add(swatch); } return(colorView); }
void AddFrameAroundFace(FaceRectangle faceRect) { NSImage image = ThePhoto.Image; // The API returns based on # of pixels, but NSImage scales, so we need to have scaled versions based on size; // The actual size of the image double imagePixelWidth = (double)image.Representations()[0].PixelsWide; double imagePixelHeight = (double)image.Representations()[0].PixelsHigh; // The photo frame itself is always square, but not every image is square CGRect photoFrame = ThePhoto.Subviews [0].Frame; photoFrame.Offset(ThePhoto.Frame.Location); // The % scaling needed in each axis double percentageX = photoFrame.Width / imagePixelWidth; double percentageY = photoFrame.Height / imagePixelHeight; // Scaled position - API gives top left, but Cocoa wants bottom left. double faceRectTopConverted = imagePixelHeight - faceRect.Top; double picX = (int)Math.Round(faceRect.Left * percentageX); double picY = (int)Math.Round(faceRectTopConverted * percentageY); // Scaled size double picWidth = (photoFrame.Width / imagePixelWidth) * faceRect.Width; double picHeight = (photoFrame.Height / imagePixelHeight) * faceRect.Height; BorderView borderView = new BorderView(new CGRect(photoFrame.X + picX, photoFrame.Y + picY - picHeight, picWidth, picHeight)); Borders.Add(borderView); View.AddSubview(borderView); }
private void SelectionChanged(object sender, EventArgsSelection <Linn.Kinsky.Source> e) { CGRect rect = iScrollView.Frame; rect.Offset(rect.Width * 1, 0); iScrollView.ScrollRectToVisible(rect, true); }
static void DrawXamagram() { var context = UIGraphics.GetCurrentContext(); var color = UIColor.FromRGBA(0.204f, 0.600f, 0.863f, 1.000f); context.SaveState(); context.TranslateCTM(257.0f, 257.0f); context.RotateCTM(90.0f * (nfloat)Math.PI / 180.0f); var polygonPath = new UIBezierPath(); polygonPath.MoveTo(new CGPoint(0.0f, -250.0f)); polygonPath.AddLineTo(new CGPoint(216.51f, -125.0f)); polygonPath.AddLineTo(new CGPoint(216.51f, 125.0f)); polygonPath.AddLineTo(new CGPoint(0.0f, 250.0f)); polygonPath.AddLineTo(new CGPoint(-216.51f, 125.0f)); polygonPath.AddLineTo(new CGPoint(-216.51f, -125.0f)); polygonPath.ClosePath(); color.SetFill(); polygonPath.Fill(); context.RestoreState(); var textRect = new CGRect(0.0f, 0.0f, 512.0f, 512.0f); var textContent = "X"; UIColor.White.SetFill(); var textFont = UIFont.FromName("Helvetica", 350.0f); textRect.Offset(0.0f, (textRect.Height - new NSString(textContent).StringSize(textFont, textRect.Size).Height) / 2.0f); new NSString(textContent).DrawString(textRect, textFont, UILineBreakMode.WordWrap, UITextAlignment.Center); }
async public Task SavehtmlToPDF() { var savePaenl = new NSSavePanel(); savePaenl.CanCreateDirectories = true; savePaenl.CanSelectHiddenExtension = false; savePaenl.Message = "Choose the path to save the document"; savePaenl.Prompt = "Save"; savePaenl.NameFieldStringValue = "LexisNexis-Document"; string title = PublicationsDataManager.SharedInstance.CurrentPublication.Name; savePaenl.BeginSheet(NSApplication.SharedApplication.KeyWindow, (nint result) => { if (result == 1) { PdfDocument pdfDocument = new PdfDocument(); CGRect documentRect = ContentWebView.MainFrame.FrameView.DocumentView.Frame; CGRect frameRect = ContentWebView.MainFrame.FrameView.Frame; CGRect pageRect = new CGRect(0, 0, frameRect.Width, frameRect.Height); CGRect pRect = ContentWebView.MainFrame.FrameView.DocumentView.RectForPage(1); int index = 0; while (pageRect.Y < documentRect.Height) { var pdfData = ContentWebView.MainFrame.FrameView.DocumentView.DataWithPdfInsideRect(pageRect); var image = new NSImage(pdfData); string footer = "Currency date: " + PublicationsDataManager.SharedInstance.CurrentPublication.CurrencyDate.Value.ToString("dd MMM yyyy") + " " + "© 2015 LexisNexis" + " " + "Printed page " + string.Format("{0}", index + 1); var footerPage = new FooterPdfPage(image); footerPage.PageHeader = title; footerPage.PageFooter = footer; pdfDocument.InsertPage(footerPage, index); index++; pageRect.Offset(0, frameRect.Height); } string fileName = savePaenl.Filename; int length = fileName.Length; if (length > 4 && fileName.Substring(length - 3).ToLower() == "pdf") { } else { fileName += ".pdf"; } string filePath = Path.Combine(Utility.GetAppCacheAbsolutePath(), fileName); pdfDocument.Write(filePath); } }); }
/// <summary> /// Dismisses the action sheet date picker /// </summary> public void Hide(bool animated) { CGRect frame = datePickerView.Frame; UIView.Animate(0.2, () => { frame.Offset(0, 100); datePickerView.Frame = frame; datePickerView.Alpha = 0; }); datePickerView.RemoveFromSuperview(); }
private void PageChanged(object sender, EventArgs e) { nint page = iPageControl.CurrentPage; CGRect rect = iScrollView.Frame; rect.Offset(rect.Width * page, 0); iScrollView.ScrollRectToVisible(rect, true); iPageControlUsed = true; }
public override CGRect EditingRect(CGRect forBounds) { CGRect rectOrigValue = base.EditingRect(forBounds); // Only apply if we set it if (this._bApplyTextOffset) { rectOrigValue.Offset(this._pTextOffset); } return(rectOrigValue); }
//#pragma mark - Layout. public CGRect MMButtonRectMake(CGRect rect, CGRect contentRect, UIUserInterfaceIdiom interfaceIdiom) { rect.Offset(contentRect.X, contentRect.Y); if (interfaceIdiom == UIUserInterfaceIdiom.Pad) { nfloat inset = MMNumberKeyboardPadSpacing / 2.0f; rect = rect.Inset(inset, inset); } return(rect); }
/// <summary> /// Dismisses the action sheet date picker /// </summary> public async Task Hide(bool animated) { CGRect frame = datePickerView.Frame; await UIView.AnimateAsync(0.2, () => { frame.Offset(0, 100); datePickerView.Frame = frame; datePickerView.Alpha = 0; }); datePickerView.RemoveFromSuperview(); }
/// <summary> /// Shows the action sheet picker from the view that was set as the owner. /// </summary> public async void Show() { // declare vars float titleBarHeight = 40; CGSize doneButtonSize = new CGSize(71, 30); CGSize actionSheetSize = new CGSize(owner.Frame.Width, datePicker.Frame.Height + titleBarHeight); CGRect datePickerFrame = new CGRect(0, owner.Frame.Height - actionSheetSize.Height , actionSheetSize.Width, actionSheetSize.Height); // show the action sheet and add the controls to it //actionSheet.ShowInView (owner); owner.AddSubview(datePickerView); // Set the Y offset of the frame 100, so that it can be brought back upwards in a slide animation datePickerFrame.Offset(0, 100); // resize the date picker frame to fit our other stuff datePickerView.Frame = datePickerFrame; // move our picker to be at the bottom of the actionsheet (view coords are relative to the action sheet) datePicker.Frame = new CGRect ((nfloat)datePicker.Frame.X, titleBarHeight, datePicker.Frame.Width, datePicker.Frame.Height); // move our label to the top of the action sheet titleLabel.Frame = new CGRect(10, 4, owner.Frame.Width - 100, 35); // move our button doneButton.Frame = new CGRect(actionSheetSize.Width - doneButtonSize.Width - 10, 7, doneButtonSize.Width, doneButtonSize.Height); // First set the alpha of the datePickerView to 0 to prepare for a fade in animation datePickerView.Alpha = 0; // Store datePickerView.Frame in the temporary variable to allow it to be animated datePickerFrame = datePickerView.Frame; await UIView.AnimateAsync(0.2, () => { datePickerFrame.Offset(0, -100); datePickerView.Frame = datePickerFrame; datePickerView.Alpha = 1; }); }
public void AnimateTransition(IUIViewControllerContextTransitioning transitionContext) { var toController = transitionContext.GetViewControllerForKey(UITransitionContext.ToViewControllerKey); var fromController = transitionContext.GetViewControllerForKey(UITransitionContext.FromViewControllerKey); var animationDuration = TransitionDuration(transitionContext); if (presenting) { transitionContext.ContainerView.AddSubview(toController.View); var finalFrame = transitionContext.GetFinalFrameForViewController(toController); var frame = new CGRect(finalFrame.Location, finalFrame.Size); frame.Offset(0.0f, transitionContext.ContainerView.Frame.Height - 20); toController.View.Frame = frame; toController.View.Alpha = 0.5f; AnimationExtensions.Animate(animationDuration, Curves.CardInCurve, () => { toController.View.Frame = finalFrame; toController.View.Alpha = 1.0f; }, () => transitionContext.CompleteTransition(!transitionContext.TransitionWasCancelled)); } else { var initialFrame = transitionContext.GetInitialFrameForViewController(fromController); initialFrame.Offset(0.0f, transitionContext.ContainerView.Frame.Height); var finalFrame = initialFrame; if (transitionContext.IsInteractive) { UIView.Animate( animationDuration, () => fromController.View.Frame = finalFrame, () => transitionContext.CompleteTransition(!transitionContext.TransitionWasCancelled) ); } else { AnimationExtensions.Animate(animationDuration, Curves.CardOutCurve, () => { fromController.View.Frame = finalFrame; fromController.View.Alpha = 0.5f; }, () => transitionContext.CompleteTransition(!transitionContext.TransitionWasCancelled)); } } }
public AppDelegate() { var style = NSWindowStyle.Closable | NSWindowStyle.Resizable | NSWindowStyle.Titled; var screenSize = NSScreen.MainScreen.Frame.Size; var rect = new CGRect(0, 0, 1024, 768); rect.Offset((screenSize.Width - rect.Width) / 2, (screenSize.Height - rect.Height) / 2); window = new NSWindow(rect, style, NSBackingStore.Buffered, false) { Title = "Xamarin.Essentials", TitleVisibility = NSWindowTitleVisibility.Hidden, }; }
/* * Render the page here: we assume we are already in a normalized coordinate system which maps * our standard aspect ratio (3:4) to (1:1) * The reason why we do this is to reuse the same drawing code for both the preview and the * full screen; for full screen rendering, we map the whole view, whereas the preview maps * the whole preview image to a quarter of the page. * */ public CGRect [] RenderPage(Page page, CGSize size, bool unstyledDrawing) { var pageRect = new CGRect(0, 0, size.Width, size.Height); var paragraphBounds = new CGRect [page.Paragraphs.Count]; using (var ctxt = UIGraphics.GetCurrentContext()) { // fill background ctxt.SetFillColor(UIColor.FromHSBA(0.11f, 0.2f, 1, 1).CGColor); ctxt.FillRect(pageRect); pageRect = pageRect.Inset(20, 20); int i = 0; foreach (var p in page.Paragraphs) { var bounds = new CGRect(pageRect.X, pageRect.Y, 0, 0); if (UnstyledDrawing) { var text = new NSString(page.StringForParagraph(p)); var font = UIFont.FromName("HoeflerText-Regular", 24); // draw text with the old legacy path, setting the font color to black. ctxt.SetFillColor(UIColor.Black.CGColor); bounds.Size = text.DrawString(pageRect, font); } else { // TODO: draw attributed text with new string drawing var text = page.AttributedStringForParagraph(p); var textContext = new NSStringDrawingContext(); text.DrawString(pageRect, NSStringDrawingOptions.UsesLineFragmentOrigin, textContext); bounds = textContext.TotalBounds; bounds.Offset(pageRect.X, pageRect.Y); } paragraphBounds [i++] = bounds; pageRect.Y += bounds.Height; } return(paragraphBounds); } }
public override void AnimateTransition(IUIViewControllerContextTransitioning transitionContext) { var fromViewController = transitionContext.GetViewControllerForKey(UITransitionContext.FromViewControllerKey); var toViewController = transitionContext.GetViewControllerForKey(UITransitionContext.ToViewControllerKey); UIView containerView = transitionContext.ContainerView; var fromView = transitionContext.GetViewFor(UITransitionContext.FromViewKey); var toView = transitionContext.GetViewFor(UITransitionContext.ToViewKey); var fromFrame = transitionContext.GetInitialFrameForViewController(fromViewController); var toFrame = transitionContext.GetFinalFrameForViewController(toViewController); var offset = new CGVector(0f, 0f); if (targetEdge == UIRectEdge.Left) { offset = new CGVector(-1f, 0f); } else if (targetEdge == UIRectEdge.Right) { offset = new CGVector(1f, 0f); } fromView.Frame = fromFrame; CGRect auxFrame = toFrame; auxFrame.Offset(toFrame.Width * offset.dx * -1f, toFrame.Height * offset.dy * -1f); toView.Frame = auxFrame; containerView.AddSubview(toView); var duration = TransitionDuration(transitionContext); UIView.Animate(duration, 0, UIViewAnimationOptions.TransitionNone, () => { var fromFrameAux = fromFrame; fromFrameAux.Offset(fromFrame.Width * offset.dx, fromFrame.Height * offset.dy); fromView.Frame = fromFrameAux; toView.Frame = toFrame; }, () => { transitionContext.CompleteTransition(!transitionContext.TransitionWasCancelled); } ); }
protected void HandleDrag(UIPanGestureRecognizer recognizer) { // if it's just began, cache the location of the image if (recognizer.State == UIGestureRecognizerState.Began) { originalImageFrame = imgDragMe.Frame; } if (recognizer.State != (UIGestureRecognizerState.Cancelled | UIGestureRecognizerState.Failed | UIGestureRecognizerState.Possible)) { // move the shape by adding the offset to the object's frame CGPoint offset = recognizer.TranslationInView(imgDragMe); CGRect newFrame = originalImageFrame; newFrame.Offset(offset.X, offset.Y); imgDragMe.Frame = newFrame; } }
private void HandleDrag(UIPanGestureRecognizer recognizer) { // If it's just began, cache the location of the image if (recognizer.State == UIGestureRecognizerState.Began) { originalImageFrame = DragImage.Frame; } // Move the image if the gesture is valid if (recognizer.State != (UIGestureRecognizerState.Cancelled | UIGestureRecognizerState.Failed | UIGestureRecognizerState.Possible)) { // Move the image by adding the offset to the object's frame CGPoint offset = recognizer.TranslationInView(DragImage); CGRect newFrame = originalImageFrame; newFrame.Offset(offset.X, offset.Y); DragImage.Frame = newFrame; } }
public override void AwakeFromNib() { base.AwakeFromNib(); scrollView.ContentSize = new CGSize(scrollView.Frame.Width * 3, scrollView.Frame.Height); scrollView.Delegate = new Delegate(scrollView, pageControl); viewControllerRoomSource.View.Frame = new CGRect(scrollView.Frame.Width * 0, 0, scrollView.Frame.Width, scrollView.Frame.Height); scrollView.AddSubview(viewControllerRoomSource.View); viewControllerNowPlaying.View.Frame = new CGRect(scrollView.Frame.Width * 1, 0, scrollView.Frame.Width, scrollView.Frame.Height); scrollView.AddSubview(viewControllerNowPlaying.View); viewControllerBrowser.View.Frame = new CGRect(scrollView.Frame.Width * 2, 0, scrollView.Frame.Width, scrollView.Frame.Height); scrollView.AddSubview(viewControllerBrowser.View); pageControl.CurrentPage = 1; CGRect rect = scrollView.Frame; rect.Offset(rect.Width * 1, 0); scrollView.ScrollRectToVisible(rect, false); iOsVersionLessThan5 = !UIDevice.CurrentDevice.CheckSystemVersion(5, 0); }
/// <summary> /// Shows the action sheet picker from the view that was set as the owner. /// </summary> public void Show () { // declare vars float titleBarHeight = 40; CGSize doneButtonSize = new CGSize (71, 30); CGSize actionSheetSize = new CGSize (owner.Frame.Width, DatePicker.Frame.Height + titleBarHeight); CGRect datePickerFrame = new CGRect (0, owner.Frame.Height - actionSheetSize.Height , actionSheetSize.Width, actionSheetSize.Height); // show the action sheet and add the controls to it //actionSheet.ShowInView (owner); owner.AddSubview (datePickerView); // Set the Y offset of the frame 100, so that it can be brought back upwards in a slide animation datePickerFrame.Offset (0, 100); // resize the date picker frame to fit our other stuff datePickerView.Frame = datePickerFrame; // move our picker to be at the bottom of the actionsheet (view coords are relative to the action sheet) DatePicker.Frame = new CGRect ((nfloat)DatePicker.Frame.X, titleBarHeight, DatePicker.Frame.Width, DatePicker.Frame.Height); // move our label to the top of the action sheet titleLabel.Frame = new CGRect (10, 4, owner.Frame.Width - 100, 35); // move our button doneButton.Frame = new CGRect (actionSheetSize.Width - doneButtonSize.Width - 10, 7, doneButtonSize.Width, doneButtonSize.Height); // First set the alpha of the datePickerView to 0 to prepare for a fade in animation datePickerView.Alpha = 0; // Store datePickerView.Frame in the temporary variable to allow it to be animated datePickerFrame = datePickerView.Frame; UIView.Animate (0.2, () => { datePickerFrame.Offset (0, -100); datePickerView.Frame = datePickerFrame; datePickerView.Alpha = 1; }); }
public static SCNNode SCBoxNode (string title, CGRect frame, NSColor color, float cornerRadius, bool centered) { NSMutableDictionary titleAttributes = null; NSMutableDictionary centeredTitleAttributes = null; // create and extrude a bezier path to build the box var path = NSBezierPath.FromRoundedRect (frame, cornerRadius, cornerRadius); path.Flatness = 0.05f; var shape = SCNShape.Create (path, 20); shape.ChamferRadius = 0.0f; var node = SCNNode.Create (); node.Geometry = shape; // create an image and fill with the color and text var textureSize = new CGSize (); textureSize.Width = NMath.Ceiling (frame.Size.Width * 1.5f); textureSize.Height = NMath.Ceiling (frame.Size.Height * 1.5f); var texture = new NSImage (textureSize); texture.LockFocus (); var drawFrame = new CGRect (0, 0, textureSize.Width, textureSize.Height); nfloat hue, saturation, brightness, alpha; (color.UsingColorSpace (NSColorSpace.DeviceRGBColorSpace)).GetHsba (out hue, out saturation, out brightness, out alpha); var lightColor = NSColor.FromDeviceHsba (hue, saturation - 0.2f, brightness + 0.3f, alpha); lightColor.Set (); NSGraphics.RectFill (drawFrame); NSBezierPath fillpath = null; if (cornerRadius == 0 && centered == false) { //special case for the "labs" slide drawFrame.Offset (0, -2); fillpath = NSBezierPath.FromRoundedRect (drawFrame, cornerRadius, cornerRadius); } else { drawFrame.Inflate (-3, -3); fillpath = NSBezierPath.FromRoundedRect (drawFrame, cornerRadius, cornerRadius); } color.Set (); fillpath.Fill (); // draw the title if any if (title != null) { if (titleAttributes == null) { var paraphStyle = new NSMutableParagraphStyle (); paraphStyle.LineBreakMode = NSLineBreakMode.ByWordWrapping; paraphStyle.Alignment = NSTextAlignment.Center; paraphStyle.MinimumLineHeight = 38; paraphStyle.MaximumLineHeight = 38; var font = NSFont.FromFontName ("Myriad Set Semibold", 34) != null ? NSFont.FromFontName ("Myriad Set Semibold", 34) : NSFont.FromFontName ("Avenir Medium", 34); var shadow = new NSShadow (); shadow.ShadowOffset = new CGSize (0, -2); shadow.ShadowBlurRadius = 4; shadow.ShadowColor = NSColor.FromDeviceWhite (0.0f, 0.5f); titleAttributes = new NSMutableDictionary (); titleAttributes.SetValueForKey (font, NSAttributedString.FontAttributeName); titleAttributes.SetValueForKey (NSColor.White, NSAttributedString.ForegroundColorAttributeName); titleAttributes.SetValueForKey (shadow, NSAttributedString.ShadowAttributeName); titleAttributes.SetValueForKey (paraphStyle, NSAttributedString.ParagraphStyleAttributeName); var centeredParaphStyle = (NSMutableParagraphStyle)paraphStyle.MutableCopy (); centeredParaphStyle.Alignment = NSTextAlignment.Center; centeredTitleAttributes = new NSMutableDictionary (); centeredTitleAttributes.SetValueForKey (font, NSAttributedString.FontAttributeName); centeredTitleAttributes.SetValueForKey (NSColor.White, NSAttributedString.ForegroundColorAttributeName); centeredTitleAttributes.SetValueForKey (shadow, NSAttributedString.ShadowAttributeName); centeredTitleAttributes.SetValueForKey (paraphStyle, NSAttributedString.ParagraphStyleAttributeName); } var attrString = new NSAttributedString (title, centered ? centeredTitleAttributes : titleAttributes); var textSize = attrString.Size; //check if we need two lines to draw the text var twoLines = title.Contains ("\n"); if (!twoLines) twoLines = textSize.Width > frame.Size.Width && title.Contains (" "); //if so, we need to adjust the size to center vertically if (twoLines) textSize.Height += 38; if (!centered) drawFrame.Inflate (-15, 0); //center vertically var dy = (drawFrame.Size.Height - textSize.Height) * 0.5f; var drawFrameHeight = drawFrame.Size.Height; drawFrame.Size = new CGSize (drawFrame.Size.Width, drawFrame.Size.Height - dy); attrString.DrawString (drawFrame); } texture.UnlockFocus (); //set the created image as the diffuse texture of our 3D box var front = SCNMaterial.Create (); front.Diffuse.Contents = texture; front.LocksAmbientWithDiffuse = true; //use a lighter color for the chamfer and sides var sides = SCNMaterial.Create (); sides.Diffuse.Contents = lightColor; node.Geometry.Materials = new SCNMaterial[] { front, sides, sides, sides, sides }; return node; }
public static UIImage Resize( UIImage sourceImage, CGSize requestedSize, ResizeMethod resizeMethod = ResizeMethod.Stretch, ResizeAlignment resizeAlignment = ResizeAlignment.CenterCenter, bool antiAliasing = true, CGInterpolationQuality interpolationQuality = CGInterpolationQuality.High, UIColor paddingColor = null) { if (paddingColor == null) { paddingColor = UIColor.Clear; } var sourceImageSize = (CGSize)sourceImage.Size; var scaleWidth = ((float)requestedSize.Width / (float)sourceImageSize.Width); var scaleHeight = ((float)requestedSize.Height / (float)sourceImageSize.Height); CGSize destImageSize; CGRect sourceBlitRect = CGRect.Empty; CGRect destBlitRect = CGRect.Empty; bool alignSourceBlitRect = false; bool alignDestBlitRect = false; switch (resizeMethod) { case ResizeMethod.AspectFit: sourceBlitRect = new CGRect(CGPoint.Empty, sourceImageSize); scaleWidth = Math.Min(scaleWidth, scaleHeight); scaleHeight = Math.Min(scaleWidth, scaleHeight); destBlitRect.Width = sourceImageSize.Width * scaleWidth; destBlitRect.Height = sourceImageSize.Height * scaleHeight; destImageSize = destBlitRect.Size; break; case ResizeMethod.AspectFitPadded: sourceBlitRect = new CGRect(CGPoint.Empty, sourceImageSize); scaleWidth = Math.Min(scaleWidth, scaleHeight); scaleHeight = Math.Min(scaleWidth, scaleHeight); destBlitRect.Width = sourceImageSize.Width * scaleWidth; destBlitRect.Height = sourceImageSize.Height * scaleHeight; destImageSize = requestedSize; alignDestBlitRect = true; break; case ResizeMethod.AspectFill: var sourceAspect = sourceImageSize.Width / sourceImageSize.Height; var destAspect = requestedSize.Width / requestedSize.Height; if (destAspect > sourceAspect) { sourceBlitRect = new CGRect(0, 0, sourceImageSize.Width, sourceImageSize.Width / destAspect); alignSourceBlitRect = true; } else if (destAspect < sourceAspect) { sourceBlitRect = new CGRect(0, 0, sourceImageSize.Height * destAspect, sourceImageSize.Height); alignSourceBlitRect = true; } else { sourceBlitRect = new CGRect(CGPoint.Empty, sourceImageSize); } destBlitRect = new CGRect(CGPoint.Empty, requestedSize); destImageSize = requestedSize; break; case ResizeMethod.Stretch: default: sourceBlitRect = new CGRect(CGPoint.Empty, sourceImageSize); destBlitRect.Width = sourceImageSize.Width * scaleWidth; destBlitRect.Height = sourceImageSize.Height * scaleHeight; destImageSize = requestedSize; break; } if (alignDestBlitRect) { switch (resizeAlignment) { case ResizeAlignment.TopLeft: destBlitRect.Offset(0, 0); break; case ResizeAlignment.TopCenter: destBlitRect.Offset((destImageSize.Width - destBlitRect.Width) / 2, 0); break; case ResizeAlignment.TopRight: destBlitRect.Offset(destImageSize.Width - destBlitRect.Width, 0); break; case ResizeAlignment.CenterLeft: destBlitRect.Offset(0, (destImageSize.Height - destBlitRect.Height) / 2); break; case ResizeAlignment.CenterCenter: destBlitRect.Offset((destImageSize.Width - destBlitRect.Width) / 2, (destImageSize.Height - destBlitRect.Height) / 2); break; case ResizeAlignment.CenterRight: destBlitRect.Offset((destImageSize.Width - destBlitRect.Width), (destImageSize.Height - destBlitRect.Height) / 2); break; case ResizeAlignment.BottomLeft: destBlitRect.Offset(0, (destImageSize.Height - destBlitRect.Height)); break; case ResizeAlignment.BottomCenter: destBlitRect.Offset((destImageSize.Width - destBlitRect.Width) / 2, destImageSize.Height - destBlitRect.Height); break; case ResizeAlignment.BottomRight: destBlitRect.Offset(destImageSize.Width - destBlitRect.Width, destImageSize.Height - destBlitRect.Height); break; default: break; } } if (alignSourceBlitRect) { switch (resizeAlignment) { case ResizeAlignment.TopLeft: sourceBlitRect.Offset(0, 0); break; case ResizeAlignment.TopCenter: sourceBlitRect.Offset((sourceImageSize.Width - sourceBlitRect.Width) / 2, 0); break; case ResizeAlignment.TopRight: sourceBlitRect.Offset(sourceImageSize.Width - sourceBlitRect.Width, 0); break; case ResizeAlignment.CenterLeft: sourceBlitRect.Offset(0, (sourceImageSize.Height - sourceBlitRect.Height) / 2); break; case ResizeAlignment.CenterCenter: sourceBlitRect.Offset((sourceImageSize.Width - sourceBlitRect.Width) / 2, (sourceImageSize.Height - sourceBlitRect.Height) / 2); break; case ResizeAlignment.CenterRight: sourceBlitRect.Offset((sourceImageSize.Width - sourceBlitRect.Width), (sourceImageSize.Height - sourceBlitRect.Height) / 2); break; case ResizeAlignment.BottomLeft: sourceBlitRect.Offset(0, sourceImageSize.Height - sourceBlitRect.Height); break; case ResizeAlignment.BottomCenter: sourceBlitRect.Offset((sourceImageSize.Width - sourceBlitRect.Width) / 2, sourceImageSize.Height - sourceBlitRect.Height); break; case ResizeAlignment.BottomRight: sourceBlitRect.Offset((sourceImageSize.Width - sourceBlitRect.Width), sourceImageSize.Height - sourceBlitRect.Height); break; default: break; } } var imageToUse = alignSourceBlitRect ? Crop(sourceImage, sourceBlitRect) : sourceImage; UIGraphics.BeginImageContext(destImageSize); var context = UIGraphics.GetCurrentContext(); //context.TranslateCTM(0, destImageSize.Height); //context.ScaleCTM(1f, -1f); context.InterpolationQuality = interpolationQuality; context.SetAllowsAntialiasing(antiAliasing); context.SetFillColor(paddingColor.CGColor); context.FillRect(new CGRect(CGPoint.Empty, destImageSize)); //context.DrawImage(destBlitRect, imageToUse.CGImage); imageToUse.Draw(destBlitRect); UIImage resizedImage = UIGraphics.GetImageFromCurrentImageContext(); UIGraphics.EndImageContext(); if (imageToUse != sourceImage) { imageToUse.Dispose(); } return(resizedImage); }
public override void ViewDidLoad() { base.ViewDidLoad(); var padding = 40; swatchSize = (float)(View.Frame.Width - padding * 2) / 3f; var rowRect = new CGRect(40, swatchSize, swatchSize, swatchSize); var primaryColor = ColorRGB.FromHex("#F04C3B"); // Row var primary = new ColorSwatchView(rowRect, primaryColor, "Primary\n" + primaryColor.ToHex()); Add(primary); rowRect.Offset(swatchSize, 0); var colorLightened = primaryColor.Lightened(); var lighter = new ColorSwatchView(rowRect, colorLightened, "Lighter\n" + colorLightened.ToHex()); Add(lighter); rowRect.Offset(swatchSize, 0); var colorDarkened = primaryColor.Darkened(); var darker = new ColorSwatchView(rowRect, colorDarkened, "Darker\n" + colorDarkened.ToHex()); Add(darker); // Row 2 rowRect.Offset(-swatchSize * 2, swatchSize); var colorSaturated = primaryColor.Saturated(); var saturated = new ColorSwatchView(rowRect, colorSaturated, "Saturated\n" + colorSaturated.ToHex()); Add(saturated); rowRect.Offset(swatchSize, 0); var colorDesaturated = primaryColor.Desaturated(); var desaturated = new ColorSwatchView(rowRect, colorDesaturated, "Desaturated\n" + colorDesaturated.ToHex()); Add(desaturated); rowRect.Offset(swatchSize, 0); var colorGray = primaryColor.GrayScale(); var grayscaled = new ColorSwatchView(rowRect, colorGray, "Grayscale\n" + colorGray.ToHex()); Add(grayscaled); // Row 32 rowRect.Offset(-swatchSize * 2, swatchSize); var colorAdjusted = primaryColor.AdjustHue(45); var adjusted = new ColorSwatchView(rowRect, colorAdjusted, "Adjusted\n" + colorAdjusted.ToHex()); Add(adjusted); rowRect.Offset(swatchSize, 0); var colorCompliment = primaryColor.Complementary(); var compliment = new ColorSwatchView(rowRect, colorCompliment, "Compliment\n" + colorCompliment.ToHex()); Add(compliment); rowRect.Offset(swatchSize, 0); var colorInverted = primaryColor.Inverted(); var invert = new ColorSwatchView(rowRect, colorInverted, "Invert\n" + colorInverted.ToHex()); Add(invert); // Row3 rowRect.Offset(-swatchSize * 2, swatchSize); var colorMixBlue = primaryColor.Mix(ConvertColor(UIColor.Blue)); var mixBlue = new ColorSwatchView(rowRect, colorMixBlue, "Mix Blue\n" + colorMixBlue.ToHex()); Add(mixBlue); rowRect.Offset(swatchSize, 0); var colorMixGreen = primaryColor.Mix(ConvertColor(UIColor.Green)); var mixGreen = new ColorSwatchView(rowRect, colorMixGreen, "Mix Green\n" + colorMixGreen.ToHex()); Add(mixGreen); rowRect.Offset(swatchSize, 0); var colorMixYellow = primaryColor.Mix(ConvertColor(UIColor.Yellow)); var mixYellow = new ColorSwatchView(rowRect, colorMixYellow, "Mix Yellow\n" + colorMixYellow.ToHex()); Add(mixYellow); // Row 5 3 rowRect.Offset(-swatchSize * 2, swatchSize); var colorTinted = primaryColor.Tinted(); var tint = new ColorSwatchView(rowRect, colorTinted, "Tint\n" + colorTinted.ToHex()); Add(tint); rowRect.Offset(swatchSize, 0); var colorShaded = primaryColor.Shaded(); var shade = new ColorSwatchView(rowRect, colorShaded, "Shade\n" + colorShaded.ToHex()); Add(shade); }
public static SCNNode SCBoxNode(string title, CGRect frame, NSColor color, float cornerRadius, bool centered) { NSMutableDictionary titleAttributes = null; NSMutableDictionary centeredTitleAttributes = null; // create and extrude a bezier path to build the box var path = NSBezierPath.FromRoundedRect(frame, cornerRadius, cornerRadius); path.Flatness = 0.05f; var shape = SCNShape.Create(path, 20); shape.ChamferRadius = 0.0f; var node = SCNNode.Create(); node.Geometry = shape; // create an image and fill with the color and text var textureSize = new CGSize(); textureSize.Width = (float)Math.Ceiling((double)frame.Size.Width * 1.5); textureSize.Height = (float)Math.Ceiling((double)frame.Size.Height * 1.5); var texture = new NSImage(textureSize); texture.LockFocus(); var drawFrame = new CGRect(0, 0, textureSize.Width, textureSize.Height); nfloat hue, saturation, brightness, alpha; (color.UsingColorSpace(NSColorSpace.DeviceRGBColorSpace)).GetHsba(out hue, out saturation, out brightness, out alpha); var lightColor = NSColor.FromDeviceHsba(hue, saturation - 0.2f, brightness + 0.3f, alpha); lightColor.Set(); NSGraphics.RectFill(drawFrame); NSBezierPath fillpath = null; if (cornerRadius == 0 && centered == false) { //special case for the "labs" slide drawFrame.Offset(0, -2); fillpath = NSBezierPath.FromRoundedRect(drawFrame, cornerRadius, cornerRadius); } else { drawFrame.Inflate(-3, -3); fillpath = NSBezierPath.FromRoundedRect(drawFrame, cornerRadius, cornerRadius); } color.Set(); fillpath.Fill(); // draw the title if any if (title != null) { if (titleAttributes == null) { var paraphStyle = new NSMutableParagraphStyle(); paraphStyle.LineBreakMode = NSLineBreakMode.ByWordWrapping; paraphStyle.Alignment = NSTextAlignment.Center; paraphStyle.MinimumLineHeight = 38; paraphStyle.MaximumLineHeight = 38; var font = NSFont.FromFontName("Myriad Set Semibold", 34) != null?NSFont.FromFontName("Myriad Set Semibold", 34) : NSFont.FromFontName("Avenir Medium", 34); var shadow = new NSShadow(); shadow.ShadowOffset = new CGSize(0, -2); shadow.ShadowBlurRadius = 4; shadow.ShadowColor = NSColor.FromDeviceWhite(0.0f, 0.5f); titleAttributes = new NSMutableDictionary(); titleAttributes.SetValueForKey(font, NSAttributedString.FontAttributeName); titleAttributes.SetValueForKey(NSColor.White, NSAttributedString.ForegroundColorAttributeName); titleAttributes.SetValueForKey(shadow, NSAttributedString.ShadowAttributeName); titleAttributes.SetValueForKey(paraphStyle, NSAttributedString.ParagraphStyleAttributeName); var centeredParaphStyle = (NSMutableParagraphStyle)paraphStyle.MutableCopy(); centeredParaphStyle.Alignment = NSTextAlignment.Center; centeredTitleAttributes = new NSMutableDictionary(); centeredTitleAttributes.SetValueForKey(font, NSAttributedString.FontAttributeName); centeredTitleAttributes.SetValueForKey(NSColor.White, NSAttributedString.ForegroundColorAttributeName); centeredTitleAttributes.SetValueForKey(shadow, NSAttributedString.ShadowAttributeName); centeredTitleAttributes.SetValueForKey(paraphStyle, NSAttributedString.ParagraphStyleAttributeName); } var attrString = new NSAttributedString(title, centered ? centeredTitleAttributes : titleAttributes); var textSize = attrString.Size; //check if we need two lines to draw the text var twoLines = title.Contains("\n"); if (!twoLines) { twoLines = textSize.Width > frame.Size.Width && title.Contains(" "); } //if so, we need to adjust the size to center vertically if (twoLines) { textSize.Height += 38; } if (!centered) { drawFrame.Inflate(-15, 0); } //center vertically var dy = (drawFrame.Size.Height - textSize.Height) * 0.5f; var drawFrameHeight = drawFrame.Size.Height; drawFrame.Size = new CGSize(drawFrame.Size.Width, drawFrame.Size.Height - dy); attrString.DrawString(drawFrame); } texture.UnlockFocus(); //set the created image as the diffuse texture of our 3D box var front = SCNMaterial.Create(); front.Diffuse.Contents = texture; front.LocksAmbientWithDiffuse = true; //use a lighter color for the chamfer and sides var sides = SCNMaterial.Create(); sides.Diffuse.Contents = lightColor; node.Geometry.Materials = new SCNMaterial[] { front, sides, sides, sides, sides }; return(node); }
//#pragma mark - Layout. public CGRect MMButtonRectMake(CGRect rect, CGRect contentRect, UIUserInterfaceIdiom interfaceIdiom){ rect.Offset( contentRect.X, contentRect.Y); if (interfaceIdiom == UIUserInterfaceIdiom.Pad) { nfloat inset = MMNumberKeyboardPadSpacing / 2.0f; rect = rect.Inset( inset, inset); } return rect; }
private void DrawCanvasMain(UIColor colorMainBackGroundStart, UIColor colorMainBackGroundEnd, CGRect menuLogoFrame) { // General Declarations var colorSpace = CGColorSpace.CreateDeviceRGB(); var context = UIGraphics.GetCurrentContext(); // Color Declarations var colorTextWhiteFade = UIColor.FromRGBA(1.000f, 1.000f, 1.000f, 0.8f); var colorTextOuterShadowColor = UIColor.FromRGBA(0.000f, 0.000f, 0.000f, 0.55f); var colorTextNumbersShadowColor = UIColor.FromRGBA(0.000f, 0.000f, 0.000f, 0.6f); // Gradient Declarations var gradientBackGroundColors = new CGColor [] { colorMainBackGroundStart.CGColor, colorMainBackGroundStart.CGColor, colorMainBackGroundEnd.CGColor }; var gradientBackGroundLocations = new nfloat [] { 0.0f, 0.1f, 1.0f }; var gradientBackGround = new CGGradient(colorSpace, gradientBackGroundColors, gradientBackGroundLocations); // Shadow Declarations var colorTextNathansWayShadow = colorTextOuterShadowColor.CGColor; var colorTextNathansWayShadowOffset = new CGSize(-38.0f, -11.0f); var colorTextNathansWayShadowBlurRadius = 5.0f; var colorTextNumbersShadow = colorTextNumbersShadowColor.CGColor; var colorTextNumbersShadowOffset = new CGSize(26.0f, 15.0f); var colorTextNumbersShadowBlurRadius = 5.0f; // Variable Declarations var strAppName = "MainMenu-Appname".Aspylate(); var strStudentName = "MainMenu-Student".Aspylate(); var strTeacherName = "MainMenu-Teacher".Aspylate(); string strLogoNathansWay = "MainMenu-Logo1".Aspylate(); string strLogo1234567890 = "MainMenu-Logo2".Aspylate(); // FrameBackdropWhite Drawing var frameBackdropWhitePath = UIBezierPath.FromRect(menuLogoFrame); UIColor.White.SetFill(); frameBackdropWhitePath.Fill(); // MainFrame Drawing var mainFramePath = UIBezierPath.FromRect(menuLogoFrame); context.SaveState(); mainFramePath.AddClip(); context.DrawLinearGradient(gradientBackGround, new CGPoint(512.0f, -0.0f), new CGPoint(512.0f, 768.0f), 0); context.RestoreState(); // NathansWay { } // textLogoNathansWay Drawing CGRect textLogoNathansWayRect = new CGRect(0.0f, 0.0f, 350.0f, 70.0f); { var textContent = "nathansway"; context.SaveState(); context.SetShadow(colorTextNathansWayShadowOffset, colorTextNathansWayShadowBlurRadius, colorTextNathansWayShadow); colorTextWhiteFade.SetFill(); var textLogoNathansWayFont = UIFont.FromName("HelveticaNeue-Light", 50.0f); textLogoNathansWayRect.Offset(0.0f, (textLogoNathansWayRect.Height - new NSString(textContent).StringSize(textLogoNathansWayFont, textLogoNathansWayRect.Size).Height) / 2.0f); new NSString(strLogoNathansWay).DrawString(textLogoNathansWayRect, textLogoNathansWayFont, UILineBreakMode.WordWrap, UITextAlignment.Center); context.RestoreState(); } // textNumberDisplay Drawing CGRect textNumberDisplayRect = new CGRect(94.0f, 44.0f, 330.0f, 74.0f); { var textContent = "1234567890"; context.SaveState(); context.SetShadow(colorTextNumbersShadowOffset, colorTextNumbersShadowBlurRadius, colorTextNumbersShadow); colorTextWhiteFade.SetFill(); var textNumberDisplayFont = UIFont.FromName("Helvetica-Light", 40.0f); textNumberDisplayRect.Offset(0.0f, (textNumberDisplayRect.Height - new NSString(textContent).StringSize(textNumberDisplayFont, textNumberDisplayRect.Size).Height) / 2.0f); new NSString(strLogo1234567890).DrawString(textNumberDisplayRect, textNumberDisplayFont, UILineBreakMode.WordWrap, UITextAlignment.Center); context.RestoreState(); } // textNumbers Drawing CGRect textNumbersRect = new CGRect(86.0f, 28.0f, 228.0f, 66.0f); UIColor.Gray.SetFill(); new NSString(strAppName).DrawString(textNumbersRect, UIFont.FromName("Helvetica-Light", 50.0f), UILineBreakMode.WordWrap, UITextAlignment.Center); // templateButtonLesson Drawing var templateButtonLessonPath = UIBezierPath.FromRoundedRect(new CGRect(51.0f, 257.0f, 446.0f, 150.0f), this._buttonMenuCornerRadius); UIColor.White.SetFill(); templateButtonLessonPath.Fill(); // templateButtonToolBox Drawing var templateButtonToolBoxPath = UIBezierPath.FromRoundedRect(new CGRect(527.0f, 257.0f, 446.0f, 150.0f), this._buttonMenuCornerRadius); UIColor.White.SetFill(); templateButtonToolBoxPath.Fill(); // templateButtonTeacher Drawing var templateButtonTeacherPath = UIBezierPath.FromRoundedRect(new CGRect(51.0f, 417.0f, 446.0f, 150.0f), this._buttonMenuCornerRadius); UIColor.White.SetFill(); templateButtonTeacherPath.Fill(); // templateButtonStudent Drawing var templateButtonStudentPath = UIBezierPath.FromRoundedRect(new CGRect(527.0f, 417.0f, 446.0f, 150.0f), this._buttonMenuCornerRadius); UIColor.White.SetFill(); templateButtonStudentPath.Fill(); // templateButtonLessonEdit Drawing var templateButtonLessonEditPath = UIBezierPath.FromRoundedRect(new CGRect(51.0f, 577.0f, 446.0f, 150.0f), this._buttonMenuCornerRadius); UIColor.White.SetFill(); templateButtonLessonEditPath.Fill(); // templateButtonVisuals Drawing var templateButtonVisualsPath = UIBezierPath.FromRoundedRect(new CGRect(527.0f, 577.0f, 446.0f, 150.0f), this._buttonMenuCornerRadius); UIColor.White.SetFill(); templateButtonVisualsPath.Fill(); // ComboBoxGroupFrame Drawing var comboBoxGroupFramePath = UIBezierPath.FromRoundedRect(new CGRect(51.0f, 124.5f, 924.0f, 120.0f), 6.0f); colorTextWhiteFade.SetStroke(); comboBoxGroupFramePath.LineWidth = 1.0f; comboBoxGroupFramePath.Stroke(); // TeacherFrame Drawing var teacherFramePath = UIBezierPath.FromRoundedRect(new CGRect(76.0f, 180.0f, 400.0f, 44.0f), 4.0f); colorTextWhiteFade.SetStroke(); teacherFramePath.LineWidth = 1.0f; teacherFramePath.Stroke(); // StudentFrame Drawing var studentFramePath = UIBezierPath.FromRoundedRect(new CGRect(550.0f, 180.0f, 400.0f, 44.0f), 4.0f); colorTextWhiteFade.SetStroke(); studentFramePath.LineWidth = 1.0f; studentFramePath.Stroke(); //// textNumbers 2 Drawing CGRect textNumbers2Rect = new CGRect(76.0f, 132.0f, 400.0f, 40.0f); UIColor.White.SetFill(); new NSString(strTeacherName).DrawString(textNumbers2Rect, UIFont.FromName("Helvetica-Light", 30.0f), UILineBreakMode.WordWrap, UITextAlignment.Left); //// textNumbers 3 Drawing CGRect textNumbers3Rect = new CGRect(550.0f, 132.0f, 400.0f, 40.0f); UIColor.White.SetFill(); new NSString(strStudentName).DrawString(textNumbers3Rect, UIFont.FromName("Helvetica-Light", 30.0f), UILineBreakMode.WordWrap, UITextAlignment.Left); }
public void RestrainViewPort(float offsetLeft, float offsetTop, float offsetRight, float offsetBottom) { contentRect.Offset(offsetLeft, offsetTop); contentRect.Size = new CGSize(chartWidth - offsetRight, chartHeight - offsetBottom); }
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(); }
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(); }
private void DrawStringOutline(CGContext context, string text, CGColor color, CGRect rect, int align) { NSString nsString = new NSString(text); int halign = align % 3; int valign = align / 3; /* * var attributesText = new NSAttributedString("Outline", * new CoreText.CTStringAttributes() * { * ForegroundColor = color, * Font = m_font * }); * var attributesOutline = new NSAttributedString("Outline", * new CoreText.CTStringAttributes() * { * ForegroundColor = m_colorWhite, * Font = m_font * }); */ var objectsText = new object[] { m_font, NSColor.FromCGColor(color) }; var keysText = new object[] { "NSFont", "NSColor" }; var attributesText = NSDictionary.FromObjectsAndKeys(objectsText, keysText); var objectsOutline = new object[] { m_font, NSColor.White }; var keysOutline = new object[] { "NSFont", "NSColor" }; var attributesOutline = NSDictionary.FromObjectsAndKeys(objectsOutline, keysOutline); CGSize size = nsString.StringSize(attributesText); if (halign == 0) { } else if (halign == 1) { rect.X = (rect.Left + rect.Right) / 2 - size.Width / 2; } else if (halign == 2) { rect.X = rect.Right - size.Width; } rect.Width = size.Width; if (valign == 0) { } else if (valign == 1) { rect.Y = (rect.Top + rect.Bottom) / 2 - size.Height / 2; } else if (valign == 2) { rect.Y = rect.Bottom - size.Height; } rect.Height = size.Height; NSColor.Black.Set(); for (int ox = -1; ox <= 1; ox++) { for (int oy = -1; oy <= 1; oy++) { CGRect rectString = rect; rectString.Offset(new CGPoint(ox, oy)); nsString.DrawString(Invert(rectString), attributesOutline); } } nsString.DrawString(Invert(rect), attributesText); //nsString.DrawString(Invert(rect), null); /* * using (var textLine = new CoreText.CTLine(attributesText)) * { * textLine.Draw(context); * } */ }
/* * Render the page here: we assume we are already in a normalized coordinate system which maps * our standard aspect ratio (3:4) to (1:1) * The reason why we do this is to reuse the same drawing code for both the preview and the * full screen; for full screen rendering, we map the whole view, whereas the preview maps * the whole preview image to a quarter of the page. * */ public CGRect [] RenderPage (Page page, CGSize size, bool unstyledDrawing) { var pageRect = new CGRect (0, 0, size.Width, size.Height); var paragraphBounds = new CGRect [page.Paragraphs.Count]; using (var ctxt = UIGraphics.GetCurrentContext ()) { // fill background ctxt.SetFillColor (UIColor.FromHSBA (0.11f, 0.2f, 1, 1).CGColor); ctxt.FillRect (pageRect); pageRect = pageRect.Inset (20, 20); int i = 0; foreach (var p in page.Paragraphs) { var bounds = new CGRect (pageRect.X, pageRect.Y, 0, 0); if (UnstyledDrawing) { var text = new NSString (page.StringForParagraph (p)); var font = UIFont.FromName ("HoeflerText-Regular", 24); // draw text with the old legacy path, setting the font color to black. ctxt.SetFillColor (UIColor.Black.CGColor); bounds.Size = text.DrawString (pageRect, font); } else { // TODO: draw attributed text with new string drawing var text = page.AttributedStringForParagraph (p); var textContext = new NSStringDrawingContext (); text.DrawString (pageRect, NSStringDrawingOptions.UsesLineFragmentOrigin, textContext); bounds = textContext.TotalBounds; bounds.Offset (pageRect.X, pageRect.Y); } paragraphBounds [i++] = bounds; pageRect.Y += bounds.Height; } return paragraphBounds; } }