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 = sd.Size.Truncate(extent.Size); if (newsize.IsEmpty) return image; var tintedImage = new NSImage(newsize); 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; return tintedImage; }
/// <summary> /// Generates the image. /// </summary> /// <returns>The image.</returns> /// <param name="view">View.</param> public static NSImage GenerateImage(this NSView view) { RectangleF bounds = view.Bounds; NSBitmapImageRep bir = view.BitmapImageRepForCachingDisplayInRect (bounds); bir.Size = bounds.Size; view.CacheDisplay (bounds, bir); NSImage targetImage = new NSImage(bounds.Size); targetImage.LockFocus(); bir.DrawInRect(bounds); targetImage.UnlockFocus(); return targetImage; }
public static NSImage ScaleImageSquare(NSImage sourceImage, int size) { var newSize = new SizeF(size, size); var newImage = new NSImage(newSize); newImage.LockFocus(); sourceImage.Size = newSize; NSGraphicsContext.CurrentContext.ImageInterpolation = NSImageInterpolation.High; sourceImage.DrawInRect(new RectangleF(0, 0, size, size), new RectangleF(), NSCompositingOperation.Copy, 1); //sourceImage.Draw(new PointF(), new RectangleF(0, 0, newSize.Width, newSize.Height), NSCompositingOperation.Copy, 1); newImage.UnlockFocus(); return newImage; }
// Create the set of display lists for the bitmaps bool MakeGLDisplayListFirst (char first, int count, int baseDL) { int curListIndex; NSColor blackColor; NSMutableDictionary attribDict; int dListNum; NSString currentChar; char currentUnichar; SizeF charSize; RectangleF charRect; 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 NSMutableDictionary (); attribDict.SetValueForKey (font, NSAttributedString.FontAttributeName); attribDict.SetValueForKey (NSColor.White, NSAttributedString.ForegroundColorAttributeName); attribDict.SetValueForKey (blackColor, NSAttributedString.BackgroundColorAttributeName); charRect.Location.X = charRect.Location.Y = 0; theImage = new NSImage (new SizeF (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); theImage.UnlockFocus (); if (!MakeDisplayList(dListNum, theImage)) { retval = false; break; } } } return retval; }
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 CCTexture2D CreateTextSprite(string text, CCFontDefinition textDefinition) { if (string.IsNullOrEmpty(text)) return new CCTexture2D(); int imageWidth; int imageHeight; var textDef = textDefinition; var contentScaleFactorWidth = CCLabel.DefaultTexelToContentSizeRatios.Width; var contentScaleFactorHeight = CCLabel.DefaultTexelToContentSizeRatios.Height; textDef.FontSize *= contentScaleFactorWidth; textDef.Dimensions.Width *= contentScaleFactorWidth; textDef.Dimensions.Height *= contentScaleFactorHeight; //bool hasPremultipliedAlpha; // font NSFont font = null; var ext = System.IO.Path.GetExtension(textDef.FontName); if (!String.IsNullOrEmpty(ext) && ext.ToLower() == ".ttf") { try { textDef.FontName = LoadFontFile(textDef.FontName); font = NSFont.FromFontName(textDef.FontName, textDef.FontSize); } catch { CCLog.Log(".ttf {0} file not found or can not be loaded.", textDef.FontName); } } else { // font font = NSFontManager.SharedFontManager.FontWithFamily(textDef.FontName, NSFontTraitMask.Unbold | NSFontTraitMask.Unitalic, 0, textDef.FontSize); } if (font == null) { font = NSFontManager.SharedFontManager.FontWithFamily("Arial", NSFontTraitMask.Unbold | NSFontTraitMask.Unitalic, 0, textDef.FontSize); CCLog.Log("{0} not found. Defaulting to Arial.", textDef.FontName); } // color var foregroundColor = NSColor.White; // alignment var horizontalAlignment = textDef.Alignment; var verticleAlignement = textDef.LineAlignment; var textAlign = (CCTextAlignment.Right == horizontalAlignment) ? NSTextAlignment.Right : (CCTextAlignment.Center == horizontalAlignment) ? NSTextAlignment.Center : NSTextAlignment.Left; // LineBreak var lineBreak = (CCLabelLineBreak.Character == textDef.LineBreak) ? NSLineBreakMode.CharWrapping : (CCLabelLineBreak.Word == textDef.LineBreak) ? NSLineBreakMode.ByWordWrapping : NSLineBreakMode.Clipping; var nsparagraphStyle = new NSMutableParagraphStyle(); nsparagraphStyle.SetParagraphStyle(NSMutableParagraphStyle.DefaultParagraphStyle); nsparagraphStyle.LineBreakMode = lineBreak; nsparagraphStyle.Alignment = textAlign; // Create a new attributed string definition var nsAttributes = new NSStringAttributes (); // Font attribute nsAttributes.Font = font; nsAttributes.ForegroundColor = foregroundColor; nsAttributes.ParagraphStyle = nsparagraphStyle; var stringWithAttributes = new NSAttributedString(text, nsAttributes); var realDimensions = stringWithAttributes.Size; // Mac crashes if the width or height is 0 if (realDimensions == SizeF.Empty) { CCLog.Log("Native string:", "Dimensions of native NSAttributedString can not be 0,0"); return new CCTexture2D(); } var dimensions = new SizeF(textDef.Dimensions.Width, textDef.Dimensions.Height); var layoutAvailable = true; // // * Note * This seems to only effect Mac because iOS works fine without this work around. // Right Alignment BoundingRectWithSize does not seem to be working correctly when the following conditions are set: // 1) Alignment Right // 2) No dimensions // 3) There are new line characters embedded in the string. // // So we set alignment to Left, calculate our bounds and then restore alignement afterwards before drawing. // if (dimensions.Width <= 0) { dimensions.Width = 8388608; layoutAvailable = false; // Set our alignment variables to left - see notes above. nsparagraphStyle.Alignment = NSTextAlignment.Left; stringWithAttributes.Dispose(); stringWithAttributes = null; stringWithAttributes = new NSAttributedString(text, nsAttributes); } if (dimensions.Height <= 0) { dimensions.Height = 8388608; layoutAvailable = false; } // Calculate our bounding rectangle var boundingRect = stringWithAttributes.BoundingRectWithSize(new SizeF((int)dimensions.Width, (int)dimensions.Height), NSStringDrawingOptions.UsesLineFragmentOrigin); if (!layoutAvailable) { if (dimensions.Width == 8388608) { dimensions.Width = boundingRect.Width; // Restore our alignment before drawing - see notes above. nsparagraphStyle.Alignment = textAlign; stringWithAttributes.Dispose(); stringWithAttributes = null; stringWithAttributes = new NSAttributedString(text, nsAttributes); } if (dimensions.Height == 8388608) { dimensions.Height = boundingRect.Height; } } imageWidth = (int)dimensions.Width; imageHeight = (int)dimensions.Height; // Alignment var xOffset = 0.0f; switch (textAlign) { case NSTextAlignment.Left: xOffset = 0; break; case NSTextAlignment.Center: xOffset = (dimensions.Width-boundingRect.Width)/2.0f; break; case NSTextAlignment.Right: xOffset = dimensions.Width-boundingRect.Width; break; default: break; } // Line alignment var yOffset = (CCVerticalTextAlignment.Top == verticleAlignement || boundingRect.Height >= dimensions.Height) ? (dimensions.Height - boundingRect.Height) // align to top : (CCVerticalTextAlignment.Bottom == verticleAlignement) ? 0 // align to bottom : (imageHeight - boundingRect.Height) / 2.0f; // align to center //Find the rect that the string will draw into inside the dimensions var drawRect = new RectangleF(xOffset , yOffset , boundingRect.Width , boundingRect.Height); NSImage image = null; try { //Set antialias or not NSGraphicsContext.CurrentContext.ShouldAntialias = textDef.isShouldAntialias; image = new NSImage(new SizeF(imageWidth, imageHeight)); image.LockFocus(); // set a default transform var transform = new NSAffineTransform(); transform.Set(); stringWithAttributes.DrawInRect(drawRect); image.UnlockFocus(); // We will use Texture2D from stream here instead of CCTexture2D stream. var tex = Texture2D.FromStream(CCDrawManager.SharedDrawManager.XnaGraphicsDevice, image); // Debugging purposes // var path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); // var fileName = Path.Combine(path, "Label3.png"); // using (var stream = new FileStream(fileName, FileMode.Create, FileAccess.Write)) // { // tex.SaveAsPng(stream, imageWidth, imageHeight); // } // Create our texture of the label string. var texture = new CCTexture2D(tex); return texture; } catch (Exception exc) { CCLog.Log ("CCLabel: Error creating native label:{0}\n{1}", exc.Message, exc.StackTrace); } finally { // clean up the resources if (image != null) { image.Dispose (); image = null; } if (stringWithAttributes != null) { stringWithAttributes.Dispose (); stringWithAttributes = null; } } return new CCTexture2D (); }