public static NSImage CropImagesFromSizeToSize(NSImage sourceImage, CGSize sourceSize, CGSize destSize) { var originalWidth = sourceImage.Size.Width; var originalHeight = sourceImage.Size.Height; var corpWidth = (sourceSize.Height / destSize.Height) * destSize.Width; var numberOfFrame = originalWidth / sourceSize.Width; var thumbnial_all_image = new NSImage(new CGSize(destSize.Width * numberOfFrame, destSize.Height)); thumbnial_all_image.LockFocus(); var newImageRect = new CGRect(0, 0, 0, 0); newImageRect.Size = thumbnial_all_image.Size; for (var i = 0; i < numberOfFrame; i++) { sourceImage.DrawInRect( new CGRect((destSize.Width * i), 0, destSize.Width, destSize.Height), new CGRect((sourceSize.Width * i) + (sourceSize.Width / 2) - (corpWidth / 2), 0, corpWidth, sourceSize.Height), NSCompositingOperation.SourceOver, 1); } thumbnial_all_image.UnlockFocus(); return(thumbnial_all_image); }
private NSImage CreateImageWithColor(string colorValue) { NSGraphicsContext.GlobalSaveGraphicsState(); CGSize size = new CGSize(12, 12); NSImage tintImage = new NSImage(size); tintImage.LockFocus(); float cornerRadius = 5f; CGRect rect = new CGRect(0, 0, 10, 10); NSBezierPath path = NSBezierPath.FromRoundedRect(rect, cornerRadius, cornerRadius); if (string.IsNullOrEmpty(colorValue)) { NSColor.Grid.Set(); path.Stroke(); } else { Utility.ColorWithHexColorValue(colorValue, 1.0f).SetFill(); path.Fill(); } tintImage.UnlockFocus(); CGContext context = NSGraphicsContext.CurrentContext.CGContext; return(tintImage); }
public override void MouseDragged(NSEvent ev) { _callbacks.OnDragged().MatchWith( data => { var pasteBoardItem = new NSPasteboardItem(); pasteBoardItem.SetStringForType("fuse-drag-n-drop", "public.data"); var draggingItem = new NSDraggingItem(pasteBoardItem); var imgCache = BitmapImageRepForCachingDisplayInRect(Bounds); CacheDisplay(Bounds, imgCache); var img = new NSImage(imgCache.Size); img.LockFocus(); imgCache.DrawInRect(Bounds, Bounds, NSCompositingOperation.Copy, 0.5f, true, new NSDictionary()); img.UnlockFocus(); draggingItem.SetDraggingFrame(new CGRect(Bounds.Location, img.Size), img); BeginDraggingSession(new[] { draggingItem }, ev, new DragSource(this, _space, _callbacks, data)); }, () => { BeginDraggingSession(new NSDraggingItem[0], ev, new DragSource(this, _space, _callbacks, null)); }); }
public virtual void UnlockFocus() { if (TargetImage != null) { TargetImage.UnlockFocus(); } }
void IWindow.ShowColorSelector(Color[] options) { if (changeColorNSEvent == null) { return; } var menu = new NSMenu(); foreach (var opt in options) { var item = new NSMenuItem(); var imgSize = new CoreGraphics.CGSize(50, 12); var img = new NSImage(imgSize); img.LockFocus(); using (var path = NSBezierPath.FromRect( new CoreGraphics.CGRect(0, 0, imgSize.Width, imgSize.Height))) using (var cl = opt.ToNSColor()) { cl.SetFill(); path.Fill(); } img.UnlockFocus(); item.Image = img; item.Title = ""; item.Action = new Selector("OnColorMenuItemClicked:"); item.Target = this; item.Tag = unchecked ((int)opt.ToUnsignedArgb()); menu.AddItem(item); } NSMenu.PopUpContextMenu(menu, changeColorNSEvent, changeColorLinkLabel); }
public static void DrawAnnotations(NSImage img, Annotation[] annotations) { img.LockFocus(); NSColor redColor = NSColor.Red; redColor.Set(); var context = NSGraphicsContext.CurrentContext; var cgcontext = context.CGContext; cgcontext.ScaleCTM(1, -1); cgcontext.TranslateCTM(0, -img.Size.Height); //context.IsFlipped = !context.IsFlipped; for (int i = 0; i < annotations.Length; i++) { float[] rects = ScaleLocation(annotations[i].Rectangle, (int)img.Size.Width, (int)img.Size.Height); CGRect cgRect = new CGRect( rects[0], rects[1], rects[2] - rects[0], rects[3] - rects[1]); NSBezierPath.StrokeRect(cgRect); } img.UnlockFocus(); }
public static void DrawResults(NSImage img, MultiboxGraph.Result result, float scoreThreshold) { Rectangle[] locations = ScaleLocation(result.DecodedLocations, (int)img.Size.Width, (int)img.Size.Height); img.LockFocus(); NSColor redColor = NSColor.Red; redColor.Set(); var context = NSGraphicsContext.CurrentContext; var cgcontext = context.CGContext; cgcontext.ScaleCTM(1, -1); cgcontext.TranslateCTM(0, -img.Size.Height); //context.IsFlipped = !context.IsFlipped; for (int i = 0; i < result.Scores.Length; i++) { if (result.Scores[i] > scoreThreshold) { Rectangle rect = locations[result.Indices[i]]; //img.Draw() //Trace.WriteLine(String.Format("x: {0}, y: {1}, w: {2}, h: {3}", rect.X, rect.Y, rect.Width, rect.Height)); CGRect cgRect = new CGRect(rect.X, rect.Y, rect.Width, rect.Height); //img.Draw(cgRect); //CGPath path = CGPath.FromRect(cgRect); //NSBezierPath path = NSBezierPath.FromOvalInRect(cgRect); //path.Fill(); //path.Stroke(); NSBezierPath.StrokeRect(cgRect); //img.Draw(cgRect, ); } } img.UnlockFocus(); }
public static NSImage ResizeNSImage(this NSImage image, double desiredWidth, double desiredHeight, InterpolationMode interpolationMode) { double widthRatio = desiredWidth / image.Size.Width; double heightRatio = desiredHeight / image.Size.Height; double scaleRatio = Math.Min(widthRatio, heightRatio); if (desiredWidth == 0) { scaleRatio = heightRatio; } if (desiredHeight == 0) { scaleRatio = widthRatio; } double aspectWidth = image.Size.Width * scaleRatio; double aspectHeight = image.Size.Height * scaleRatio; var newSize = new CGSize(aspectWidth, aspectHeight); var resizedImage = new NSImage(newSize); resizedImage.LockFocus(); image.Draw(new CGRect(CGPoint.Empty, newSize), CGRect.Empty, NSCompositingOperation.SourceOver, 1.0f); resizedImage.UnlockFocus(); return(resizedImage); }
internal static async Task <StorageItemThumbnail> CreatePhotoThumbnailAsync(StorageFile file) { #if __MAC__ NSImage image = NSImage.FromStream(await file.OpenStreamForReadAsync()); double ratio = image.Size.Width / image.Size.Height; NSImage newImage = new NSImage(new CGSize(240, 240 * ratio)); newImage.LockFocus(); image.Size = newImage.Size; image.Draw(new CGPoint(0, 0), new CGRect(0, 0, newImage.Size.Width, newImage.Size.Height), NSCompositingOperation.Copy, 1.0f); newImage.UnlockFocus(); NSMutableData buffer = new NSMutableData(); CGImageDestination dest = CGImageDestination.Create(buffer, UTType.JPEG, 1); dest.AddImage(newImage.CGImage); return(new StorageItemThumbnail(buffer.AsStream())); #else UIImage image = UIImage.FromFile(file.Path); UIImage image2 = image.Scale(new CGSize(240, 240)); image.Dispose(); return(new StorageItemThumbnail(image2.AsJPEG().AsStream())); #endif }
public static NSImage MergeImages(List <NSImage> images) { var thumbnail_width = images.First().Size.Width; var imageHeight = images.First().Size.Height; var thumbnial_all_image = new NSImage(new CGSize(thumbnail_width * images.Count, imageHeight)); thumbnial_all_image.LockFocus(); var newImageRect = new CGRect(0, 0, 0, 0); newImageRect.Size = thumbnial_all_image.Size; int index = 0; foreach (var i in images) { i.DrawInRect( new CGRect(thumbnail_width * index, 0, thumbnail_width, imageHeight), new CGRect(0, 0, thumbnail_width, imageHeight), NSCompositingOperation.SourceOver, 1); ++index; } thumbnial_all_image.UnlockFocus(); return(thumbnial_all_image); }
public static NSImage Tint(this NSImage image, NSColor tint) { var colorGenerator = new CIConstantColorGenerator { Color = CIColor.FromCGColor(tint.CGColor) }; var colorFilter = new CIColorControls { Image = (CIImage)colorGenerator.ValueForKey(CIFilterOutputKey.Image), Saturation = 3f, Brightness = 0.35f, Contrast = 1f }; var monochromeFilter = new CIColorMonochrome { Image = CIImage.FromCGImage(image.CGImage), Color = CIColor.FromRgb(0.75f, 0.75f, 0.75f), Intensity = 1f }; var compositingFilter = new CIMultiplyCompositing { Image = (CIImage)colorFilter.ValueForKey(CIFilterOutputKey.Image), BackgroundImage = (CIImage)monochromeFilter.ValueForKey(CIFilterOutputKey.Image) }; var outputImage = (CIImage)compositingFilter.ValueForKey(CIFilterOutputKey.Image); var extent = outputImage.Extent; var newsize = Size.Truncate(extent.Size.ToEto()); if (newsize.IsEmpty) { return(image); } var tintedImage = new NSImage(newsize.ToNS()); tintedImage.LockFocus(); try { var graphics = NSGraphicsContext.CurrentContext.GraphicsPort; var ciContext = CIContext.FromContext(graphics, new CIContextOptions { UseSoftwareRenderer = true }); ciContext.DrawImage(outputImage, extent, extent); } finally { tintedImage.UnlockFocus(); } var newrep = tintedImage.Representations()[0]; newrep.Size = image.Size; tintedImage.Size = image.Size; return(tintedImage); }
public static NSImage Resize(this NSImage image, CGSize destSize, NSImageScalingMode scalingMode, NSImageSizing sizingMode) { var sourceSize = image.Size; var wantToScaleUp = (destSize.Height > sourceSize.Height || destSize.Width > sourceSize.Width); var canScaleUp = (NSImageSizing.Up & sizingMode) == NSImageSizing.Up; var wantToScaleDown = (destSize.Height < sourceSize.Height || destSize.Width < sourceSize.Width); var canScaleDown = (NSImageSizing.Down & sizingMode) == NSImageSizing.Down; if (!canScaleDown && wantToScaleDown) { sourceSize.Width = destSize.Width; sourceSize.Height = destSize.Height; } if (!canScaleUp && wantToScaleUp) { destSize.Width = sourceSize.Width; destSize.Height = sourceSize.Height; } var destRect = new CGRect(0, 0, destSize.Width, destSize.Height); var sourceRect = new CGRect(0, 0, sourceSize.Width, sourceSize.Height); var targetImage = new NSImage(destSize); if (scalingMode != NSImageScalingMode.ScaleToFill) { float ratioH = (float)(destSize.Height / sourceSize.Height); float ratioW = (float)(destSize.Width / sourceSize.Width); var fill = scalingMode == NSImageScalingMode.ScaleAspectFill; var h = ratioH >= ratioW; if ((fill && !h) || (h && !fill)) { var newSize = new CGSize(sourceSize.Width, destSize.Height / ratioW); sourceRect = new CGRect(sourceRect.Location, newSize); } else { var newSize = new CGSize(Math.Floor(destSize.Width / ratioH), sourceSize.Height); sourceRect = new CGRect(sourceRect.Location, newSize); } } var newX = Math.Floor((sourceSize.Width - sourceRect.Size.Width) / 2); var newY = Math.Floor((sourceSize.Height - sourceRect.Size.Height) / 2); sourceRect.Location = new CGPoint(newX, newY); targetImage.LockFocus(); image.DrawInRect(destRect, sourceRect, NSCompositingOperation.Copy, 1.0f); targetImage.UnlockFocus(); return(targetImage); }
internal static NSImage ResizeImage(NSImage image, CGSize size) { var resized = new NSImage(size); resized.LockFocus(); NSGraphicsContext.CurrentContext.ImageInterpolation = NSImageInterpolation.High; image.DrawInRect(new CGRect(0, 0, size.Width, size.Height), new CGRect(CGPoint.Empty, image.Size), NSCompositingOperation.Copy, 1.0f); resized.UnlockFocus(); return(resized); }
public static void Colourize(NSView control, Color color, Action drawAction) { var size = control.Frame.Size; if (size.Width <= 0 || size.Height <= 0) { return; } var image = new NSImage(size); image.LockFocusFlipped(control.IsFlipped); drawAction(); image.UnlockFocus(); var ciImage = CIImage.FromCGImage(image.CGImage); SD.SizeF realSize; if (control.RespondsToSelector(selConvertSizeToBacking)) { realSize = control.ConvertSizeToBacking(size); } else { realSize = control.ConvertSizeToBase(size); } if (control.IsFlipped) { var affineTransform = new NSAffineTransform(); affineTransform.Translate(0, realSize.Height); affineTransform.Scale(1, -1); var filter1 = new CIAffineTransform(); filter1.Image = ciImage; filter1.SetValueForKey(affineTransform, CIInputTransform); ciImage = filter1.ValueForKey(CIOutputImage) as CIImage; } var filter2 = new CIColorControls(); filter2.SetDefaults(); filter2.Image = ciImage; filter2.Saturation = 0.0f; ciImage = filter2.ValueForKey(CIOutputImage) as CIImage; var filter3 = new CIColorMatrix(); filter3.SetDefaults(); filter3.Image = ciImage; filter3.RVector = new CIVector(0, color.R, 0); filter3.GVector = new CIVector(color.G, 0, 0); filter3.BVector = new CIVector(0, 0, color.B); ciImage = filter3.ValueForKey(CIOutputImage) as CIImage; ciImage.Draw(new SD.RectangleF(SD.PointF.Empty, size), new SD.RectangleF(SD.PointF.Empty, realSize), NSCompositingOperation.SourceOver, 1); }
public void End() { if (_image == null) { return; } _image.UnlockFocus(); var cgImage = _image.CGImage; var ciImage = CIImage.FromCGImage(cgImage); #pragma warning disable CS0618 // Image => InputImage in Xamarin.Mac 6.6 var filter2 = new CIColorControls(); filter2.SetDefaults(); filter2.Image = ciImage; filter2.Saturation = 0.0f; ciImage = (CIImage)filter2.ValueForKey(CIOutputImage); var filter3 = new CIColorMatrix(); filter3.SetDefaults(); filter3.Image = ciImage; #pragma warning restore CS0618 var cgColor = Color.ToCG(); var components = cgColor.Components; if (components.Length >= 3) { filter3.RVector = new CIVector(0, components[0], 0); filter3.GVector = new CIVector(components[1], 0, 0); filter3.BVector = new CIVector(0, 0, components[2]); } else if (components.Length >= 1) { // grayscale filter3.RVector = new CIVector(0, components[0], 0); filter3.GVector = new CIVector(components[0], 0, 0); filter3.BVector = new CIVector(0, 0, components[0]); } filter3.AVector = new CIVector(0, 0, 0, cgColor.Alpha); ciImage = (CIImage)filter3.ValueForKey(CIOutputImage); // create separate context so we can force using the software renderer, which is more than fast enough for this var ciContext = CIContext.FromContext(NSGraphicsContext.CurrentContext.GraphicsPort, new CIContextOptions { UseSoftwareRenderer = true }); ciContext.DrawImage(ciImage, new CGRect(CGPoint.Empty, _image.Size), new CGRect(0, 0, cgImage.Width, cgImage.Height)); ciImage.Dispose(); ciContext.Dispose(); filter2.Dispose(); filter3.Dispose(); }
private NSImage Resize(NSImage image, double width, double height) { var newImage = new NSImage(new CGSize(width, height)); newImage.LockFocus(); image.DrawInRect(new CGRect(0, 0, width, height), new CGRect(0, 0, image.Size.Width, image.Size.Height), NSCompositingOperation.SourceOver, 1); newImage.UnlockFocus(); return(newImage); }
public override void MouseDragged(NSEvent theEvent) { base.MouseDragged(theEvent); CGPoint down = mMouseDownEvent.LocationInWindow; CGPoint drag = theEvent.LocationInWindow; // Calculate the distance between this dragging position and the mouse down position double distance = Math.Sqrt(Math.Pow(down.X - drag.X, 2) + Math.Pow(down.Y - drag.Y, 2)); // Don't do too often if (distance < 3) { return; } // And not if there is no string to drag if (mLetter.Length == 0) { return; } // Get the size of the string CGSize size = mLetter.StringSize(mTextAttributes); // Create the image that will be dragged NSImage anImage = new NSImage(size); // Create a rect in which you will draw the letter // in the image CGRect imageBounds = CGRect.Empty; imageBounds.Location = new CGPoint(0.0f, 0.0f); imageBounds.Size = size; // Draw the letter on the image anImage.LockFocus(); DrawStringCenteredInRectangle(mLetter, imageBounds); anImage.UnlockFocus(); // Get the location of the mouse down event CGPoint p = this.ConvertPointFromView(down, null); // Drag from the center of theimage p = new CGPoint(p.X - size.Width / 2, p.Y - size.Height / 2); // Get the pasteboard NSPasteboard pb = NSPasteboard.FromName(NSPasteboard.NSDragPasteboardName); // Put the string and the pdf image in the pasteboard WriteToPasteBoard(pb); // Start the drag - deprecated, should use BeginDraggingSession, but need to wait for new Xam.Mac. Bug filed. #26941 this.DragImage(anImage, p, CGSize.Empty, mMouseDownEvent, pb, this, true); }
public static XIR.Image RemoteRepresentation(this NSLineJoinStyle obj) { // Customize the line cap style for the new object. var aPath = new NSBezierPath(); var lineWidth = 10; var sampleWidth = 50; // First we draw the presentation line aPath.LineWidth = lineWidth; aPath.MoveTo(new CGPoint(lineWidth, lineWidth)); aPath.LineTo(new CGPoint(lineWidth + sampleWidth / 2, sampleWidth)); aPath.LineTo(new CGPoint(lineWidth + sampleWidth, lineWidth)); switch ((NSLineJoinStyle)obj) { case NSLineJoinStyle.Bevel: aPath.LineJoinStyle = NSLineJoinStyle.Bevel; break; case NSLineJoinStyle.Miter: aPath.LineJoinStyle = NSLineJoinStyle.Miter; break; case NSLineJoinStyle.Round: aPath.LineJoinStyle = NSLineJoinStyle.Round; break; } // let's make sure we leave a little room for the line width drawing as well by adding the lineWidth as well var width = aPath.ControlPointBounds.Right + lineWidth; var height = aPath.ControlPointBounds.Bottom + lineWidth; var nsimage = new NSImage(new CGSize(width, height)); nsimage.LockFocus(); brush.Set(); aPath.Stroke(); // Second, we draw the inset line to demonstrate the bounds aPath.RemoveAllPoints(); aPath.LineWidth = 2; aPath.MoveTo(new CGPoint(lineWidth, lineWidth)); aPath.LineTo(new CGPoint(lineWidth + sampleWidth / 2, sampleWidth)); aPath.LineTo(new CGPoint(lineWidth + sampleWidth, lineWidth)); pen.Set(); aPath.Stroke(); nsimage.UnlockFocus(); return(nsimage.RemoteRepresentation()); }
public static void Colourize(NSView control, Color color, Action drawAction) { var size = control.Frame.Size; if (size.Width <= 0 || size.Height <= 0) { return; } var image = new NSImage(size); image.LockFocusFlipped(!control.IsFlipped); drawAction(); image.UnlockFocus(); var ciImage = CIImage.FromCGImage(image.CGImage); CGSize realSize; if (control.RespondsToSelector(selConvertSizeToBacking)) { realSize = control.ConvertSizeToBacking(size); } else { realSize = control.ConvertSizeToBase(size); } var filter2 = new CIColorControls(); filter2.SetDefaults(); filter2.Image = ciImage; filter2.Saturation = 0.0f; ciImage = (CIImage)filter2.ValueForKey(CIOutputImage); var filter3 = new CIColorMatrix(); filter3.SetDefaults(); filter3.Image = ciImage; filter3.RVector = new CIVector(0, color.R, 0); filter3.GVector = new CIVector(color.G, 0, 0); filter3.BVector = new CIVector(0, 0, color.B); filter3.AVector = new CIVector(0, 0, 0, color.A); ciImage = (CIImage)filter3.ValueForKey(CIOutputImage); // create separate context so we can force using the software renderer, which is more than fast enough for this var ciContext = CIContext.FromContext(NSGraphicsContext.CurrentContext.GraphicsPort, new CIContextOptions { UseSoftwareRenderer = true }); ciContext.DrawImage(ciImage, new CGRect(CGPoint.Empty, size), new CGRect(CGPoint.Empty, realSize)); }
static NSData AsEncodedBitmapData(NSImage image, NSBitmapImageFileType fileType) { if (image == null) { return(null); } image.LockFocus(); var rect = new CGRect(0, 0, image.Size.Width, image.Size.Height); var rep = new NSBitmapImageRep(rect); image.UnlockFocus(); return(rep.RepresentationUsingTypeProperties(fileType, null)); }
//- (NSImage *)thumbImageFromImage:(NSImage *)image; async Task <NSImage> ThumbImageFromImageAsync(NSImage image) { nfloat targetHeight = 200.0f; CGSize imageSize = image.Size; CGSize smallerSize = new CGSize(targetHeight * imageSize.Width / imageSize.Height, targetHeight); NSImage smallerImage = new NSImage(smallerSize); smallerImage.LockFocus(); image.DrawInRect(new CGRect(0, 0, smallerSize.Width, smallerSize.Height), CGRect.Empty, NSCompositingOperation.Copy, 1.0f); smallerImage.UnlockFocus(); return(smallerImage); }
private NSImage GetImage() { using (var src = NSImage.FromStream(System.IO.File.OpenRead(filePath))) { var imageSize = src.Size; var thumbnailSize = new CGSize(Math.Ceiling(BarHeight * imageSize.Width / imageSize.Height), BarHeight); var thumbnail = new NSImage(thumbnailSize); thumbnail.LockFocus(); src.Draw(new CGRect(CGPoint.Empty, thumbnailSize), new CGRect(CGPoint.Empty, imageSize), NSCompositingOperation.SourceOver, 1f); thumbnail.UnlockFocus(); return(thumbnail); } }
public static void Colourize(NSView control, Color color, Action drawAction) { var size = control.Frame.Size; var image = new NSImage(size); image.LockFocusFlipped(control.IsFlipped); drawAction(); image.UnlockFocus(); var ciImage = CIImage.FromData(image.AsTiff()); if (control.IsFlipped) { var realSize = control.ConvertSizeToBase(size); var affineTransform = new NSAffineTransform(); affineTransform.Translate(0, realSize.Height); affineTransform.Scale(1, -1); var filter1 = CIFilter.FromName("CIAffineTransform"); filter1.SetValueForKey(ciImage, CIInputImage); filter1.SetValueForKey(affineTransform, CIInputTransform); ciImage = filter1.ValueForKey(CIOutputImage) as CIImage; } var filter2 = CIFilter.FromName("CIColorControls"); filter2.SetDefaults(); filter2.SetValueForKey(ciImage, CIInputImage); filter2.SetValueForKey(new NSNumber(0.0f), CIInputSaturation); ciImage = filter2.ValueForKey(CIOutputImage) as CIImage; var filter3 = CIFilter.FromName("CIColorMatrix"); filter3.SetDefaults(); filter3.SetValueForKey(ciImage, CIInputImage); filter3.SetValueForKey(new CIVector(0, color.R, 0), CIInputRVector); filter3.SetValueForKey(new CIVector(color.G, 0, 0), CIInputGVector); filter3.SetValueForKey(new CIVector(0, 0, color.B), CIInputBVector); ciImage = filter3.ValueForKey(CIOutputImage) as CIImage; image = new NSImage(size); var rep = NSCIImageRep.FromCIImage(ciImage); image.AddRepresentation(rep); image.Draw(SD.PointF.Empty, new SD.RectangleF(SD.PointF.Empty, size), NSCompositingOperation.SourceOver, 1); /* Use this when implemented in maccore: * ciImage.Draw (SD.PointF.Empty, new SD.RectangleF (SD.PointF.Empty, size), NSCompositingOperation.SourceOver, 1); */ }
public static void DrawWithColorTransform(this NSView view, Color?color, Action drawDelegate) { if (color.HasValue) { var size = view.Frame.Size; if (size.Width <= 0 || size.Height <= 0) { return; } // render view to image var image = new NSImage(size); image.LockFocusFlipped(!view.IsFlipped); drawDelegate(); image.UnlockFocus(); // create Core image for transformation var ciImage = CIImage.FromCGImage(image.CGImage); CGSize displaySize; #pragma warning disable iOSAndMacApiUsageIssue if (view.RespondsToSelector(selConvertSizeToBacking)) { displaySize = view.ConvertSizeToBacking(size); } else { displaySize = view.ConvertSizeToBase(size); } #pragma warning restore iOSAndMacApiUsageIssue // apply color matrix var transformColor = new CIColorMatrix(); transformColor.SetDefaults(); transformColor.Image = ciImage; transformColor.RVector = new CIVector(0, (float)color.Value.Red, 0); transformColor.GVector = new CIVector((float)color.Value.Green, 0, 0); transformColor.BVector = new CIVector(0, 0, (float)color.Value.Blue); using (var key = new NSString("outputImage")) ciImage = (CIImage)transformColor.ValueForKey(key); var ciCtx = CIContext.FromContext(NSGraphicsContext.CurrentContext.GraphicsPort, null); ciCtx.DrawImage(ciImage, new CGRect(CGPoint.Empty, size), new CGRect(CGPoint.Empty, displaySize)); } else { drawDelegate(); } }
public static void DrawAnnotations(NSImage img, Annotation[] annotations) { img.LockFocus(); NSColor redColor = NSColor.Red; redColor.Set(); var context = NSGraphicsContext.CurrentContext; if (context == null) { return; } var cgcontext = context.CGContext; for (int i = 0; i < annotations.Length; i++) { float[] rects = ScaleLocation(annotations[i].Rectangle, (int)img.Size.Width, (int)img.Size.Height); CGRect cgRect = new CGRect( rects[0], rects[1], rects[2] - rects[0], rects[3] - rects[1]); NSFont font = NSFont.FromFontName("Arial", 20); var fontDictionary = Foundation.NSDictionary.FromObjectsAndKeys( new Foundation.NSObject[] { font, NSColor.Red }, new Foundation.NSObject[] { NSStringAttributeKey.Font, NSStringAttributeKey.ForegroundColor }); //CGSize size = text.StringSize(fontDictionary); CGPoint p = new CGPoint(cgRect.Location.X, img.Size.Height - cgRect.Location.Y); annotations[i].Label.DrawAtPoint(p, fontDictionary); } cgcontext.ScaleCTM(1, -1); cgcontext.TranslateCTM(0, -img.Size.Height); //context.IsFlipped = !context.IsFlipped; for (int i = 0; i < annotations.Length; i++) { float[] rects = ScaleLocation(annotations[i].Rectangle, (int)img.Size.Width, (int)img.Size.Height); CGRect cgRect = new CGRect( rects[0], rects[1], rects[2] - rects[0], rects[3] - rects[1]); NSBezierPath.StrokeRect(cgRect); } img.UnlockFocus(); }
public static NSImage TintColor(this NSImage image, NSColor color) { try { image.LockFocus(); color.Set(); var rect = new CGRect(0, 0, image.Size.Width, image.Size.Height); NSGraphics.RectFill(rect, NSCompositingOperation.SourceAtop); } finally { image.UnlockFocus(); } return(image); }
public UIImage GetRenderedPattern() { var patternBounds = new CGRect(0, 0, 12, 12); var bounds = new CGRect(0, 0, patternBounds.Width * patternBounds.Width, patternBounds.Height * patternBounds.Height); #if __MACOS__ var img = new NSImage(bounds.Size); img.LockFocus(); var context = NSGraphicsContext.CurrentContext.GraphicsPort; #else UIGraphics.BeginImageContextWithOptions(bounds.Size, false, 0); var context = UIGraphics.GetCurrentContext(); #endif try { context.SetStrokeColor(UIColor.Blue.CGColor); context.AddEllipseInRect(bounds); using (var patternColorSpace = CGColorSpace.CreatePattern(null)) { context.SetFillColorSpace(patternColorSpace); using (var pattern = new CGPattern(patternBounds, CGAffineTransform.MakeIdentity(), patternBounds.Width, patternBounds.Height, CGPatternTiling.ConstantSpacing, true, ctx => { ctx.SetStrokeColor(UIColor.Green.CGColor); ctx.SetLineWidth(1); ctx.MoveTo(2, 6); ctx.AddLineToPoint(10, 6); ctx.MoveTo(6, 2); ctx.AddLineToPoint(6, 10); ctx.StrokePath(); })) { context.SetFillPattern(pattern, new nfloat [] { 1 }); } } context.DrawPath(CGPathDrawingMode.FillStroke); #if __MACOS__ return(img); #else return(UIGraphics.GetImageFromCurrentImageContext()); #endif } finally { #if __MACOS__ img.UnlockFocus(); #else UIGraphics.EndImageContext(); #endif } }
public static NSImage ResizeTo(this NSImage self, CoreGraphics.CGSize newSize) { if (self == null) { return(null); } self.ResizingMode = NSImageResizingMode.Stretch; var resizedImage = new NSImage(newSize); resizedImage.LockFocus(); self.Size = newSize; NSGraphicsContext.CurrentContext.ImageInterpolation = NSImageInterpolation.High; self.Draw(CoreGraphics.CGPoint.Empty, new CoreGraphics.CGRect(0, 0, newSize.Width, newSize.Height), NSCompositingOperation.Copy, 1.0f); resizedImage.UnlockFocus(); return(resizedImage); }
NSImage MakeRotatedCopy(NSImage original, float degrees) { var copy = new NSImage(original.Size); copy.LockFocus(); try { var rot = new NSAffineTransform(); rot.Translate(original.Size.Width / 2, original.Size.Height / 2); rot.RotateByDegrees(degrees); rot.Translate(-original.Size.Width / 2, -original.Size.Height / 2); rot.Concat(); original.Draw(PointF.Empty, RectangleF.Empty, NSCompositingOperation.Copy, 1); } finally { copy.UnlockFocus(); } return(copy); }
internal static NSImage CreateSwatch(CGSize size, NSColor stroke = null, NSColor fill = null) { var image = new NSImage(size); image.LockFocus(); var context = NSGraphicsContext.CurrentContext.CGContext; var rect = new CGRect(CGPoint.Empty, size); (fill ?? NSColor.FromWhite(1.0f, 0.9f)).SetFill(); context.FillRect(rect); (stroke ?? NSColor.FromWhite(0.2f, 1.0f)).SetStroke(); context.StrokeRectWithWidth(rect, 4.0f); image.UnlockFocus(); return(image); }
static NSImage Render (string value) { NSImage image = null; NSApplication.SharedApplication.InvokeOnMainThread (() => { NSString text = new NSString (string.IsNullOrEmpty (value) ? " " : value); NSFont font = NSFont.FromFontName ("Arial", 20); var fontDictionary = NSDictionary.FromObjectsAndKeys (new NSObject[] { font, NSColor.Red }, new NSObject[] { NSStringAttributeKey.Font, NSStringAttributeKey.ForegroundColor }); CGSize size = text.StringSize (fontDictionary); image = new NSImage (new CGSize (size)); image.LockFocus (); text.DrawString (new CGPoint (0, 0), fontDictionary); image.UnlockFocus (); }); return image; }
NSImage MakeRotatedCopy (NSImage original, float degrees) { var copy = new NSImage (original.Size); copy.LockFocus (); try { var rot = new NSAffineTransform (); rot.Translate (original.Size.Width / 2, original.Size.Height / 2); rot.RotateByDegrees (degrees); rot.Translate (-original.Size.Width / 2, -original.Size.Height / 2); rot.Concat (); original.Draw (CGPoint.Empty, CGRect.Empty, NSCompositingOperation.Copy, 1); } finally { copy.UnlockFocus (); } return copy; }
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 override void MouseDragged(NSEvent theEvent) { base.MouseDragged(theEvent); CGPoint down = mMouseDownEvent.LocationInWindow; CGPoint drag = theEvent.LocationInWindow; // Calculate the distance between this dragging position and the mouse down position double distance = Math.Sqrt( Math.Pow( down.X - drag.X ,2) + Math.Pow(down.Y - drag.Y, 2) ); // Don't do too often if (distance < 3) { return; } // And not if there is no string to drag if (mLetter.Length == 0) { return; } // Get the size of the string CGSize size = mLetter.StringSize(mTextAttributes); // Create the image that will be dragged NSImage anImage = new NSImage(size); // Create a rect in which you will draw the letter // in the image CGRect imageBounds = CGRect.Empty; imageBounds.Location = new CGPoint(0.0f, 0.0f); imageBounds.Size = size; // Draw the letter on the image anImage.LockFocus(); DrawStringCenteredInRectangle(mLetter, imageBounds); anImage.UnlockFocus(); // Get the location of the mouse down event CGPoint p = this.ConvertPointFromView(down, null); // Drag from the center of theimage p = new CGPoint(p.X - size.Width/2, p.Y - size.Height/2); // Get the pasteboard NSPasteboard pb = NSPasteboard.FromName(NSPasteboard.NSDragPasteboardName); // Put the string and the pdf image in the pasteboard WriteToPasteBoard(pb); // Start the drag - deprecated, should use BeginDraggingSession, but need to wait for new Xam.Mac. Bug filed. #26941 this.DragImage(anImage, p,CGSize.Empty, mMouseDownEvent, pb, this, true); }
//- (NSImage *)thumbImageFromImage:(NSImage *)image; async Task<NSImage> ThumbImageFromImageAsync(NSImage image) { nfloat targetHeight = 200.0f; CGSize imageSize = image.Size; CGSize smallerSize = new CGSize(targetHeight * imageSize.Width / imageSize.Height, targetHeight); NSImage smallerImage = new NSImage(smallerSize); smallerImage.LockFocus(); image.DrawInRect(new CGRect(0,0,smallerSize.Width, smallerSize.Height), CGRect.Empty, NSCompositingOperation.Copy, 1.0f); smallerImage.UnlockFocus(); return smallerImage; }
// Create the set of display lists for the bitmaps bool MakeGLDisplayListFirst (char first, int count, int baseDL) { int curListIndex; NSColor blackColor; NSStringAttributes attribDict; int dListNum; NSString currentChar; char currentUnichar; CGSize charSize; CGRect charRect = CGRect.Empty; NSImage theImage; bool retval; // Make sure the list isn't already under construction GL.GetInteger (GetPName.ListIndex, out curListIndex); if (curListIndex != 0) { Console.WriteLine ("Display list already under construction"); return false; } // Save pixel unpacking state GL.PushClientAttrib (ClientAttribMask.ClientPixelStoreBit); GL.PixelStore (PixelStoreParameter.UnpackSwapBytes, 0); GL.PixelStore (PixelStoreParameter.UnpackLsbFirst, 0); GL.PixelStore (PixelStoreParameter.UnpackSkipPixels, 0); GL.PixelStore (PixelStoreParameter.UnpackSkipRows, 0); GL.PixelStore (PixelStoreParameter.UnpackRowLength, 0); GL.PixelStore (PixelStoreParameter.UnpackAlignment, 0); blackColor = NSColor.Black; attribDict = new NSStringAttributes { Font = font, ForegroundColor = NSColor.White, BackgroundColor = blackColor }; theImage = new NSImage (new CGSize (0,0)); retval = true; for (dListNum = baseDL, currentUnichar = first; currentUnichar < first + count; dListNum++, currentUnichar++) { currentChar = new NSString (Char.ToString (currentUnichar)); charSize = currentChar.StringSize (attribDict); charRect.Size = charSize; charRect = charRect.Integral (); if (charRect.Size.Width > 0 && charRect.Size.Height > 0) { theImage.Size = charRect.Size; theImage.LockFocus (); NSGraphicsContext.CurrentContext.ShouldAntialias = false; blackColor.Set (); NSBezierPath.FillRect (charRect); currentChar.DrawString (charRect, attribDict.Dictionary); theImage.UnlockFocus (); if (!MakeDisplayList(dListNum, theImage)) { retval = false; break; } } } return retval; }
private NSImage GetImage() { using (var src = NSImage.FromStream(System.IO.File.OpenRead(filePath))) { var imageSize = src.Size; var thumbnailSize = new CGSize(Math.Ceiling(BarHeight * imageSize.Width / imageSize.Height), BarHeight); var thumbnail = new NSImage(thumbnailSize); thumbnail.LockFocus(); src.Draw(new CGRect(CGPoint.Empty, thumbnailSize), new CGRect(CGPoint.Empty, imageSize), NSCompositingOperation.SourceOver, 1f); thumbnail.UnlockFocus(); return thumbnail; } }