Exemplo n.º 1
0
		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;
		}
Exemplo n.º 2
0
        /// <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;
        }
Exemplo n.º 3
0
		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);
		}
Exemplo n.º 4
0
		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);
			 */
		}
Exemplo n.º 5
0
		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);
			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));
		}
Exemplo n.º 6
0
 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;
 }
Exemplo n.º 7
0
		// 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;
		}
Exemplo n.º 8
0
		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 ();


        }