示例#1
0
        private IEnumerable <int> GetIntFromPixel(UIImage bmp)
        {
            for (var x = 0; x < bmp.Size.Width; x++)
            {
                for (var y = 0; y < bmp.Size.Height; y++)
                {
                    var rawData = new byte[4];
                    var handle  = GCHandle.Alloc(rawData);
                    try
                    {
                        using (var colorSpace = CGColorSpace.CreateDeviceRGB())
                        {
                            using (var context = new CGBitmapContext(rawData, 1, 1, 8, 4, colorSpace, CGImageAlphaInfo.PremultipliedLast))
                            {
                                context.DrawImage(new RectangleF(-x, y - Convert.ToInt32(bmp.Size.Height), Convert.ToInt32(bmp.Size.Width),
                                                                 Convert.ToInt32(bmp.Size.Height)), bmp.CGImage);

                                //float red = (rawData[0]) / 255.0f;
                                //float green = (rawData[1]) / 255.0f;
                                //float blue = (rawData[2]) / 255.0f;
                                //float alpha = (rawData[3]) / 255.0f;

                                yield return((int)rawData[2]); //B;

                                yield return((int)rawData[1]); //G;

                                yield return((int)rawData[0]); //R;

                                yield return((int)rawData[3]); //A;
                            }
                        }
                    }
                    finally
                    {
                        handle.Free();
                    }
                }
            }
        }
示例#2
0
        public void Dispose()
        {
            if (Address == IntPtr.Zero)
            {
                return;
            }
            var nfo = (int)CGBitmapFlags.ByteOrder32Big | (int)CGImageAlphaInfo.PremultipliedLast;

            using (var colorSpace = CGColorSpace.CreateDeviceRGB())
                using (var bContext = new CGBitmapContext(Address, Width, Height, 8, Width * 4,
                                                          colorSpace, (CGImageAlphaInfo)nfo))
                    using (var image = bContext.ToImage())
                        using (var context = UIGraphics.GetCurrentContext())
                        {
                            // flip the image for CGContext.DrawImage
                            context.TranslateCTM(0, _viewHeight);
                            context.ScaleCTM(1, -1);
                            context.DrawImage(new CGRect(0, 0, _viewWidth, _viewHeight), image);
                        }
            Marshal.FreeHGlobal(Address);
            Address = IntPtr.Zero;
        }
        public void Dispose()
        {
            if (Address == IntPtr.Zero)
            {
                return;
            }
            var nfo = (int)CGBitmapFlags.ByteOrder32Big | (int)CGImageAlphaInfo.PremultipliedLast;

            using (var colorSpace = CGColorSpace.CreateDeviceRGB())
                using (var bContext = new CGBitmapContext(Address, Width, Height, 8, Width * 4,
                                                          colorSpace, (CGImageAlphaInfo)nfo))
                    using (var image = bContext.ToImage())
                        using (var nscontext = NSGraphicsContext.CurrentContext)
                            using (var context = nscontext.GraphicsPort)
                            {
                                context.SetFillColor(255, 255, 255, 255);
                                context.FillRect(new CGRect(default(CGPoint), _logicalSize));
                                context.DrawImage(new CGRect(default(CGPoint), _logicalSize), image);
                            }
            Marshal.FreeHGlobal(Address);
            Address = IntPtr.Zero;
        }
示例#4
0
        public void CreateIndexed()
        {
            // from: http://developer.apple.com/library/ios/#documentation/GraphicsImaging/Reference/CGColorSpace/Reference/reference.html
            //  m is the number of color components in the base color space
            nint      m         = 3; // RGB
            const int lastIndex = 2;

            // An array of m*(lastIndex+1) bytes
            byte[] table = new byte [3 * (lastIndex + 1)] {
                1, 2, 3, 4, 5, 6, 255, 255, 255
            };
            using (var base_cs = CGColorSpace.CreateDeviceRGB())
                using (var cs = CGColorSpace.CreateIndexed(base_cs, lastIndex, table)) {
                    Assert.That(cs.Components, Is.EqualTo((nint)1), "1");
                    Assert.That(cs.Model, Is.EqualTo(CGColorSpaceModel.Indexed), "Indexed");
                    var bcs = cs.GetBaseColorSpace();
                    Assert.That(bcs.Components, Is.EqualTo(m), "Components");
                    Assert.That(base_cs.Model, Is.EqualTo(bcs.Model), "GetBaseColorSpace");
                    var new_table = cs.GetColorTable();
                    Assert.That(table, Is.EqualTo(new_table), "GetColorTable");
#if NET
                    Assert.Null(cs.GetIccProfile(), "GetIccProfile");
#else
                    Assert.Null(cs.GetICCProfile(), "GetICCProfile");
#endif
                    if (TestRuntime.CheckXcodeVersion(8, 0))
                    {
                        Assert.Null(cs.Name, "Name");
                        Assert.False(cs.IsWideGamutRgb, "IsWideGamutRgb");
                        Assert.False(cs.SupportsOutput, "SupportsOutput");
                        Assert.Null(cs.GetIccData(), "GetIccData");
                    }

                    if (TestRuntime.CheckXcodeVersion(12, 0))
                    {
                        Assert.False(cs.UsesExtendedRange, "UsesExtendedRange");
                    }
                }
        }
示例#5
0
        protected override void UpdateDetailDisplay(UITableViewCell cell)
        {
            if (cell == null || Parent == null)
            {
                return;
            }

            var  psection    = Parent as Section;
            bool roundTop    = psection?.Elements[0] == this;
            bool roundBottom = psection?.Elements[psection.Elements.Count - 1] == this;

            using (var cs = CGColorSpace.CreateDeviceRGB())
            {
                using (
                    var bit = new CGBitmapContext(IntPtr.Zero, Dimx, Dimy, 8, 0, cs, CGImageAlphaInfo.PremultipliedFirst)
                    )
                {
                    DrawClippedBitmap(roundTop, bit, roundBottom);
                    cell.ImageView.Image = UIImage.FromImage(bit.ToImage());
                }
            }
        }
    public PatternDrawingView() : base()
    {
        // First we need to create a CGPattern that specifies the qualities of our pattern.

        using (var coloredPattern = new CGPattern(
                   new RectangleF(0, 0, 16, 16),     // the pattern coordinate space, drawing is clipped to this rectangle
                   CGAffineTransform.MakeIdentity(), // a transform on the pattern coordinate space used before it is drawn.
                   16, 16,                           // the spacing (horizontal, vertical) of the pattern - how far to move after drawing each cell
                   CGPatternTiling.NoDistortion,
                   true,                             // this is a colored pattern, which means that you only specify an alpha value when drawing it
                   DrawColored)){
            // To draw a pattern, you need a pattern colorspace.
            // Since this is an colored pattern, the parent colorspace is NULL, indicating that it only has an alpha value.
            using (var coloredPatternColorSpace = CGColorSpace.CreatePattern(null)){
                float alpha = 1;

                // Since this pattern is colored, we'll create a CGColor for it to make drawing it easier and more efficient.
                // From here on, the colored pattern is referenced entirely via the associated CGColor rather than the
                // originally created CGPatternRef.
                coloredPatternColor = new CGColor(coloredPatternColorSpace, coloredPattern, new float [] { alpha });
            }
        }

        // Uncolored Pattern setup
        // As above, we create a CGPattern that specifies the qualities of our pattern
        uncoloredPattern = new CGPattern(
            new RectangleF(0, 0, 16, 16),     // coordinate space
            CGAffineTransform.MakeIdentity(), // transform
            16, 16,                           // spacing
            CGPatternTiling.NoDistortion,
            false,                            // this is an uncolored pattern, thus to draw it we need to specify both color and alpha
            DrawUncolored);                   // callbacks for this pattern

        // With an uncolored pattern we still need to create a pattern colorspace, but now we need a parent colorspace
        // We'll use the DeviceRGB colorspace here. We'll need this colorspace along with the CGPatternRef to draw this pattern later.
        using (var deviceRGB = CGColorSpace.CreateDeviceRGB()){
            uncoloredPatternColorSpace = CGColorSpace.CreatePattern(deviceRGB);
        }
    }
示例#7
0
        public byte[] ResizeImage(byte[] imageData, float width, float height)
        {
            UIImage            originalImage = ImageFromByteArray(imageData);
            UIImageOrientation orientation   = originalImage.Orientation;

            //create a 24bit RGB image
            using (CGBitmapContext context = new CGBitmapContext(IntPtr.Zero,
                                                                 (int)width, (int)height, 8,
                                                                 4 * (int)width, CGColorSpace.CreateDeviceRGB(),
                                                                 CGImageAlphaInfo.PremultipliedFirst))
            {
                RectangleF imageRect = new RectangleF(0, 0, width, height);

                // draw the image
                context.DrawImage(imageRect, originalImage.CGImage);

                UIKit.UIImage resizedImage = UIKit.UIImage.FromImage(context.ToImage(), 0, orientation);

                // save the image as a jpeg
                return(resizedImage.AsPNG().ToArray());
            }
        }
示例#8
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            // set the background color of the view to white
            View.BackgroundColor = UIColor.White;

            // instantiate a new image view that takes up the whole screen and add it to
            // the view hierarchy
            RectangleF imageViewFrame = new RectangleF(0, -NavigationController.NavigationBar.Frame.Height, View.Frame.Width, View.Frame.Height);

            imageView = new UIImageView(imageViewFrame);
            View.AddSubview(imageView);

            // create our offscreen bitmap context
            // size
            SizeF bitmapSize = new SizeF(View.Frame.Size);

            using (CGBitmapContext context = new CGBitmapContext(IntPtr.Zero, (int)bitmapSize.Width, (int)bitmapSize.Height, 8, (int)(4 * bitmapSize.Width), CGColorSpace.CreateDeviceRGB(), CGImageAlphaInfo.PremultipliedFirst)) {
                // declare vars
                RectangleF patternRect = new RectangleF(0, 0, 16, 16);

                // set the color space of our fill to be the patter colorspace
                context.SetFillColorSpace(CGColorSpace.CreatePattern(CGColorSpace.CreateDeviceRGB()));

                // create a new pattern
                CGPattern pattern = new CGPattern(patternRect, CGAffineTransform.MakeRotation(.3f)
                                                  , 16, 16, CGPatternTiling.NoDistortion, false, DrawPolkaDotPattern);

                // set our fill as our pattern, color doesn't matter because the pattern handles it
                context.SetFillPattern(pattern, new float[] { 1, 0, 0, 1 });

                // fill the entire view with that pattern
                context.FillRect(imageView.Frame);

                // output the drawing to the view
                imageView.Image = UIImage.FromImage(context.ToImage());
            }
        }
示例#9
0
        private static UIImage GetThumbImage(float thumbContentSize, int pageNumber)
        {
            if ((pageNumber <= 0) || (pageNumber > PDFDocument.PageCount))
            {
                return(null);
            }

            var pageSize = PageContentView.GetPageViewSize(pageNumber);

            if (pageSize.Width % 2 > 0)
            {
                pageSize.Width--;
            }
            if (pageSize.Height % 2 > 0)
            {
                pageSize.Height--;
            }

            var targetSize = new CGSize((int)pageSize.Width, (int)pageSize.Height);

            CGImage pageImage;

            using (CGColorSpace rgb = CGColorSpace.CreateDeviceRGB()) {
                using (var context = new CGBitmapContext(null, (int)targetSize.Width, (int)targetSize.Height, 8, 0, rgb, CGBitmapFlags.ByteOrder32Little | CGBitmapFlags.NoneSkipFirst)) {
                    using (var pdfPage = PDFDocument.GetPage(pageNumber)) {
                        var thumbRect = new CGRect(0.0f, 0.0f, targetSize.Width, targetSize.Height);
                        context.SetFillColor(1.0f, 1.0f, 1.0f, 1.0f);
                        context.FillRect(thumbRect);
                        context.ConcatCTM(pdfPage.GetDrawingTransform(CGPDFBox.Crop, thumbRect, 0, true));
                        context.SetRenderingIntent(CGColorRenderingIntent.Default);
                        context.InterpolationQuality = CGInterpolationQuality.Default;
                        context.DrawPDFPage(pdfPage);

                        pageImage = context.ToImage();
                    }
                }
            }
            return(UIImage.FromImage(pageImage));
        }
示例#10
0
 private void ConvertFromCGImage(CGImage cgImage)
 {
     //Don't do this, Xamarin.iOS won't be able to resolve: if (this is Image<Rgba, Byte>)
     if (typeof(TColor) == typeof(Rgba) && typeof(TDepth) == typeof(byte))
     {
         RectangleF rect = new RectangleF(PointF.Empty, new SizeF(cgImage.Width, cgImage.Height));
         using (CGColorSpace cspace = CGColorSpace.CreateDeviceRGB())
             using (CGBitmapContext context = new CGBitmapContext(
                        MIplImage.ImageData,
                        Width, Height,
                        8,
                        Width * 4,
                        cspace,
                        CGImageAlphaInfo.PremultipliedLast))
                 context.DrawImage(rect, cgImage);
     }
     else
     {
         using (Image <Rgba, Byte> tmp = new Image <Rgba, Byte>(cgImage))
             ConvertFrom(tmp);
     }
 }
示例#11
0
            UIImage ImageFromSampleBuffer(CMSampleBuffer sampleBuffer)
            {
                // Get the CoreVideo image
                using (var pixelBuffer = sampleBuffer.GetImageBuffer() as CVPixelBuffer){
                    // Lock the base address
                    pixelBuffer.Lock(0);
                    // Get the number of bytes per row for the pixel buffer
                    var baseAddress = pixelBuffer.BaseAddress;
                    int bytesPerRow = pixelBuffer.BytesPerRow;
                    int width       = pixelBuffer.Width;
                    int height      = pixelBuffer.Height;
                    var flags       = CGBitmapFlags.PremultipliedFirst | CGBitmapFlags.ByteOrder32Little;

                    // Create a CGImage on the RGB colorspace from the configured parameter above
                    using (var cs = CGColorSpace.CreateDeviceRGB())
                        using (var context = new CGBitmapContext(baseAddress, width, height, 8, bytesPerRow, cs, (CGImageAlphaInfo)flags))
                            using (var cgImage = context.ToImage()){
                                pixelBuffer.Unlock(0);
                                return(UIImage.FromImage(cgImage));
                            }
                }
            }
示例#12
0
        /// <summary>
        /// for debugging...
        /// </summary>
        public UIImage ImageBufferToUIImage(CVPixelBuffer imageBuffer)
        {
            //imageBuffer
            imageBuffer.Lock(CVPixelBufferLock.None);

            var baseAddress = imageBuffer.BaseAddress;
            var bytesPerRow = imageBuffer.BytesPerRow;

            var width  = imageBuffer.Width;
            var height = imageBuffer.Height;

            var colorSpace = CGColorSpace.CreateDeviceRGB();
            var bitmapInfo = (uint)CGImageAlphaInfo.NoneSkipFirst | (uint)CGBitmapFlags.ByteOrder32Little;

            var context = new CGBitmapContext(baseAddress, width, height, 8, bytesPerRow, colorSpace, (CGImageAlphaInfo)bitmapInfo);

            var quartzImage = context?.ToImage();

            imageBuffer.Unlock(CVPixelBufferLock.None);

            var image = new UIImage(quartzImage, 1.0f, UIImageOrientation.Right);

            // HACK: save as file
            //var documentsDirectory = Environment.GetFolderPath
            //			 (Environment.SpecialFolder.Personal);
            //string jpgFilename = System.IO.Path.Combine(documentsDirectory, "Photo.jpg"); // hardcoded filename, overwritten each time
            //NSData imgData = image.AsJPEG();
            //NSError err = null;
            //if (imgData.Save(jpgFilename, false, out err))
            //{
            //	Console.WriteLine("saved as " + jpgFilename);
            //}
            //else
            //{
            //	Console.WriteLine("NOT saved as " + jpgFilename + " because" + err.LocalizedDescription);
            //}

            return(image);
        }
示例#13
0
        public static UIImage HeatMapWithRect(CGRect rect, double boost, PointF[] points, double[] weights, bool weightsAdjustmentEnabled, bool groupingEnabled)
        {
            var rect1 = new Rect {
                Width = rect.Width, Height = rect.Height, X = rect.X, Y = rect.Y
            };

            var points1 = new List <PointWithWeight>();

            for (int i = 0; i < points.Length; i++)
            {
                points1.Add(new PointWithWeight(points[i].X, points[i].Y, weights[i]));
            }
            var bytes = LFHeatMap.HeatMap.HeatMapForRectangle(rect1, boost, points1.ToArray(), weightsAdjustmentEnabled, groupingEnabled);

            CGImage cgImage = null;

            using (var colorSpace = CGColorSpace.CreateDeviceRGB())
                using (var context = new CGBitmapContext(bytes, (nint)rect.Width, (nint)rect.Height, 8, 4 * (nint)rect.Width, colorSpace, CGBitmapFlags.PremultipliedLast | CGBitmapFlags.ByteOrderDefault))
                    cgImage = context.ToImage();

            return(new UIImage(cgImage));
        }
示例#14
0
        public static XIR.Image RemoteRepresentation(this CGPath cgPath)
        {
            // We add just a little padding to keep from clipping the drawings that lie on the bounds.
            var width  = (int)cgPath.PathBoundingBox.Width + 4 > 0 ? (int)cgPath.PathBoundingBox.Width + 4 : 200;
            var height = (int)cgPath.PathBoundingBox.Height + 4 > 0 ? (int)cgPath.PathBoundingBox.Height + 4 : 200;

            var bytesPerRow = width * 4;

            // We need to offset the image to keep from clipping the drawing.
            var offsetXZero = -cgPath.PathBoundingBox.X;
            var offsetYZero = -cgPath.PathBoundingBox.Y;

            // Create a transform to offset our drawing.
            var transform = CGAffineTransform.MakeIdentity();

            transform.Translate(offsetXZero + 1, offsetYZero + 1);

            using (var context = new CGBitmapContext(
                       IntPtr.Zero, width, height,
                       8, bytesPerRow, CGColorSpace.CreateDeviceRGB(),
                       CGImageAlphaInfo.PremultipliedFirst))
            {
                // Make sure we offset our drawing to keep it form clipping
                context.ConcatCTM(transform);

                context.SaveState();
                context.SetFillColor(brush.CGColor);
                context.AddPath(cgPath);
                context.FillPath();
                context.RestoreState();

                context.SetStrokeColor(pen.CGColor);
                context.SetLineWidth(1f);
                context.AddPath(cgPath);
                context.DrawPath(CGPathDrawingMode.Stroke);

                return(context.RemoteRepresentation());
            }
        }
示例#15
0
        /// <summary>
        /// Gets the rgba bytes from an image stream.
        /// </summary>
        /// <param name="imageStream">The source image stream.</param>
        /// <returns>An array containing the premultiplied RGBA bytes of the raw image</returns>
        public static byte[] GetRGBABytes(Stream imageStream)
        {
            byte[] outputData = null;

            using (var uiImage = UIImage.LoadFromData(NSData.FromStream(imageStream)))
            {
                var cgImage = uiImage.CGImage;

                var imageWidth  = (int)cgImage.Width;
                var imageHeight = (int)cgImage.Height;

                outputData = new byte[imageWidth * imageHeight * 4];

                using (var colorSpace = CGColorSpace.CreateDeviceRGB())
                    using (var bitmapContext = new CGBitmapContext(outputData, imageWidth, imageHeight, 8, imageWidth * 4, colorSpace, CGBitmapFlags.PremultipliedLast))
                    {
                        bitmapContext.DrawImage(new RectangleF(0, 0, imageWidth, imageHeight), cgImage);
                    }
            }

            return(outputData);
        }
示例#16
0
        /// <summary>
        /// Returns one dimensional byte array with pixel color info (0 - 255).
        /// Each 4 consecutive pixels represent r, g, b, a values of one pixel.
        /// Use <see cref="GetPixelColor"/> method to get a tuple with each component
        /// for a specific pixel.
        /// </summary>
        private static byte[] GetRawPixelData(UIImage image, int width, int height)
        {
            var rawData = new byte[width * height * 4];
            var handle  = GCHandle.Alloc(rawData);

            try
            {
                using (var colorSpace = CGColorSpace.CreateDeviceRGB())
                {
                    using (var context = new CGBitmapContext(rawData, width, height, 8, width * 4, colorSpace, CGImageAlphaInfo.PremultipliedLast))
                    {
                        context.DrawImage(new CGRect(0, 0, image.Size.Width, image.Size.Height), image.CGImage);

                        return(rawData);
                    }
                }
            }
            finally
            {
                handle.Free();
            }
        }
        public static CGBitmapContext ToBitmapContext(this System.Drawing.SizeF size)
        {
            using (var colorSpace = CGColorSpace.CreateDeviceRGB())
            {
                var pixelsWide = (int)size.Width;
                var pixelsHigh = (int)size.Height;

                var bitmapBytesPerRow = (pixelsWide * 4);// 1
                var bitmapByteCount   = (bitmapBytesPerRow * pixelsHigh);

                var bitmapData = new byte[bitmapByteCount];

                return(new CGBitmapContext(
                           bitmapData,
                           pixelsWide,
                           pixelsHigh,
                           8,   // bits per component
                           bitmapBytesPerRow,
                           colorSpace,
                           CGImageAlphaInfo.PremultipliedLast));
            }
        }
示例#18
0
        public byte[] ResizeImage(byte[] imageData, float width, float height, int quality)
        {
            UIImage originalImage = ImageFromByteArray(imageData);


            float oldWidth    = (float)originalImage.Size.Width;
            float oldHeight   = (float)originalImage.Size.Height;
            float scaleFactor = 0f;

            if (oldWidth > oldHeight)
            {
                scaleFactor = width / oldWidth;
            }
            else
            {
                scaleFactor = height / oldHeight;
            }

            float newHeight = oldHeight * scaleFactor;
            float newWidth  = oldWidth * scaleFactor;

            //create a 24bit RGB image
            using (CGBitmapContext context = new CGBitmapContext(IntPtr.Zero,
                                                                 (int)newWidth, (int)newHeight, 8,
                                                                 0, CGColorSpace.CreateDeviceRGB(),
                                                                 CGImageAlphaInfo.PremultipliedFirst))
            {
                RectangleF imageRect = new RectangleF(0, 0, newWidth, newHeight);

                // draw the image
                context.DrawImage(imageRect, originalImage.CGImage);

                UIImage resizedImage = UIImage.FromImage(context.ToImage());

                // save the image as a jpeg
                return(resizedImage.AsJPEG((float)quality).ToArray());
            }
        }
示例#19
0
        public Tuple <System.Drawing.Size, byte[]> ReduceImage(byte[] datas, int maxWidth)
        {
            UIImage originalImage = ImageFromByteArray(datas);

            //原图比较小,不用缩小
            if (originalImage.Size.Width <= maxWidth)
            {
                return(new Tuple <System.Drawing.Size, byte[]>(
                           new System.Drawing.Size()
                {
                    Width = (int)originalImage.Size.Width,
                    Height = (int)originalImage.Size.Height
                }, datas));
            }
            else //按比例缩小
            {
                int width  = maxWidth;
                int height = (int)(width * originalImage.Size.Height / originalImage.Size.Width);

                using (CGBitmapContext context = new CGBitmapContext(IntPtr.Zero,
                                                                     width, height, 8,
                                                                     (4 * width), CGColorSpace.CreateDeviceRGB(),
                                                                     CGImageAlphaInfo.PremultipliedFirst))
                {
                    RectangleF imageRect = new RectangleF(0, 0, width, height);

                    // draw the image
                    context.DrawImage(imageRect, originalImage.CGImage);

                    UIKit.UIImage resizedImage = UIKit.UIImage.FromImage(context.ToImage(), 0, originalImage.Orientation);

                    // save the image as a jpeg
                    return(new Tuple <System.Drawing.Size, byte[]>(
                               new System.Drawing.Size(width, height),
                               resizedImage.AsJPEG().ToArray()));
                }
            }
        }
        public void DrawContentView(RectangleF rect, CGContext context, UITableViewElementCell cell)
        {
            var gradientFrame = rect;

            var shineFrame = gradientFrame;

            shineFrame.Y     += 1;
            shineFrame.X     += 1;
            shineFrame.Width -= 2;
            shineFrame.Height = (shineFrame.Height / 2);

            CGColorSpace colorSpace = CGColorSpace.CreateDeviceRGB();

            var gradient = new CGGradient(
                colorSpace,
                new float[] { 0f, 0f, 0f, 0.70f,
                              0f, 0f, 0f, 0.40f },
                new float[] { 0, 1 });

            var shineGradient = new CGGradient(
                colorSpace,
                new float[] { 1f, 1f, 1f, 0.80f,
                              1f, 1f, 1f, 0.10f },
                new float[] { 0, 1 });

            if (Cell != null && Cell.Highlighted)
            {
                context.SetFillColorWithColor(HighlightColor.CGColor);
            }
            else
            {
                context.SetFillColorWithColor(CellBackgroundColor.CGColor);
            }
            context.FillRect(rect);

            context.DrawLinearGradient(gradient, new PointF(gradientFrame.Left, gradientFrame.Top), new PointF(gradientFrame.Left, gradientFrame.Bottom), CGGradientDrawingOptions.DrawsAfterEndLocation);
            context.DrawLinearGradient(shineGradient, new PointF(shineFrame.Left, shineFrame.Top), new PointF(shineFrame.Left, shineFrame.Bottom), CGGradientDrawingOptions.DrawsAfterEndLocation);
        }
示例#21
0
        static UIImage ProcessImageNamed(string imageName)
        {
            var image = UIImage.FromBundle(imageName);

            if (image == null)
            {
                return(null);
            }

            if (imageName.Contains(".jpg"))
            {
                return(image);
            }

            UIImage resultingImage;

            using (var colorSpace = CGColorSpace.CreateDeviceRGB()) {
                // Create a bitmap context of the same size as the image.
                var imageWidth  = (int)image.Size.Width;
                var imageHeight = (int)image.Size.Height;

                using (var bitmapContext = new CGBitmapContext(null, imageWidth, imageHeight, 8, imageHeight * 4,
                                                               colorSpace, CGBitmapFlags.PremultipliedLast | CGBitmapFlags.ByteOrder32Little)) {
                    // Draw the image into the graphics context.
                    if (image.CGImage == null)
                    {
                        throw new Exception("Unable to get a CGImage from a UIImage.");
                    }

                    bitmapContext.DrawImage(new CGRect(CGPoint.Empty, image.Size), image.CGImage);
                    using (var newImageRef = bitmapContext.ToImage()) {
                        resultingImage = new UIImage(newImageRef);
                    }
                }
            }

            return(resultingImage);
        }
示例#22
0
        public static UIImage MakeCalendarBadge(UIImage template, string smallText, string bigText)
        {
            using (var cs = CGColorSpace.CreateDeviceRGB()){
                using (var context = new CGBitmapContext(IntPtr.Zero, 59, 58, 8, 59 * 4, cs, CGImageAlphaInfo.PremultipliedLast)){
                    //context.ScaleCTM (0.5f, -1);
                    context.TranslateCTM(0, 0);
                    context.DrawImage(new RectangleF(0, 0, 59, 58), template.CGImage);
                    context.SetFillColor(0, 0, 0, 1);

                    // The _small_ string
                    context.SelectFont("Helvetica-Bold", 14f, CGTextEncoding.MacRoman);

                    // Pretty lame way of measuring strings, as documented:
                    var start = context.TextPosition.X;
                    context.SetTextDrawingMode(CGTextDrawingMode.Invisible);
                    context.ShowText(smallText);
                    var width = context.TextPosition.X - start;

                    context.SetTextDrawingMode(CGTextDrawingMode.Fill);
                    context.ShowTextAtPoint((59 - width) / 2, 10, smallText);                  // was 46

                    // The BIG string
                    context.SelectFont("Helvetica-Bold", 32, CGTextEncoding.MacRoman);
                    start = context.TextPosition.X;
                    context.SetTextDrawingMode(CGTextDrawingMode.Invisible);
                    context.ShowText(bigText);
                    width = context.TextPosition.X - start;

                    context.SetFillColor(0, 0, 0, 1);
                    context.SetTextDrawingMode(CGTextDrawingMode.Fill);
                    context.ShowTextAtPoint((59 - width) / 2, 25, bigText);                     // was 9

                    context.StrokePath();

                    return(UIImage.FromImage(context.ToImage()));
                }
            }
        }
示例#23
0
        /// <summary>
        /// This is an expensive call. Used by preview thumbnail.
        /// </summary>
        /// <returns>The (processed) video frame, as a UIImage.</returns>
        /// <param name="imageBuffer">The (processed) video frame.</param>
        public static UIImage ImageBufferToUIImage(CVPixelBuffer imageBuffer)
        {
            imageBuffer.Lock(CVPixelBufferLock.None);

            var baseAddress = imageBuffer.BaseAddress;
            var bytesPerRow = imageBuffer.BytesPerRow;

            var width  = imageBuffer.Width;
            var height = imageBuffer.Height;

            var colorSpace = CGColorSpace.CreateDeviceRGB();
            var bitmapInfo = (uint)CGImageAlphaInfo.NoneSkipFirst | (uint)CGBitmapFlags.ByteOrder32Little;

            using (var context = new CGBitmapContext(baseAddress, width, height, 8, bytesPerRow, colorSpace, (CGImageAlphaInfo)bitmapInfo))
            {
                var quartzImage = context?.ToImage();
                imageBuffer.Unlock(CVPixelBufferLock.None);

                var image = new UIImage(quartzImage, 1.0f, UIImageOrientation.Up);

                return(image);
            }
        }
示例#24
0
        public static UIImage MaskeWithColor(this UIImage image, UIColor color)
        {
            var maskImage = image.CGImage;
            var width     = image.Size.Width;
            var height    = image.Size.Height;
            var bounds    = new CGRect(0, 0, width, height);

            using (var colorSpace = CGColorSpace.CreateDeviceRGB())
            {
                using (var bitmapContext = new CGBitmapContext(null, (nint)width, (nint)height, 8, 0, colorSpace, CGImageAlphaInfo.PremultipliedLast))
                {
                    bitmapContext.ClipToMask(bounds, maskImage);
                    bitmapContext.SetFillColor(color.CGColor);
                    bitmapContext.FillRect(bounds);

                    using (var cImage = bitmapContext.ToImage())
                    {
                        var coloredImage = UIImage.FromImage(cImage);
                        return(coloredImage);
                    }
                }
            }
        }
示例#25
0
            public override void DrawInContext(CGContext ctx)
            {
                var    size = Frame.Size;
                Point  center;
                nfloat radius;

                if (_isRelative)
                {
                    center = new Point(_center.X * size.Width, _center.Y * size.Height);
                    radius = (nfloat)(_radius * size.Width + _radius * size.Height) / 2.0f;                     // We take the avg
                }
                else
                {
                    center = _center;
                    radius = _radius;
                }

                var gradient = new CGGradient(CGColorSpace.CreateDeviceRGB(), _colors, _locations);

                var startCenter = new CGPoint(center.X, center.Y);

                ctx.DrawRadialGradient(gradient, startCenter, 0, startCenter, radius, CGGradientDrawingOptions.DrawsAfterEndLocation);
            }
示例#26
0
        protected override void AddPageImpl(float width, float height)
        {
            if (_closed)
            {
                throw new Exception("Unable to add a page because the PDFContext is already closed.");
            }

            if (_tempFilePath == null)
            {
                _tempFilePath = Path.GetTempFileName();
                UIGraphics.BeginPDFContext(_tempFilePath, CGRect.Empty, _documentInfo);
            }

            var pageInfo = new NSMutableDictionary();

            UIGraphics.BeginPDFPage(new CGRect(0, 0, width, height), pageInfo);

            var context = UIGraphics.GetCurrentContext();

            context.SetFillColorSpace(CGColorSpace.CreateDeviceRGB());
            context.SetStrokeColorSpace(CGColorSpace.CreateDeviceRGB());
            _canvas.Context = context;
        }
示例#27
0
        public void CreateDeviceRGB()
        {
            using (var cs = CGColorSpace.CreateDeviceRGB()) {
                Assert.That(cs.Components, Is.EqualTo((nint)3), "3");
                Assert.That(cs.Model, Is.EqualTo(CGColorSpaceModel.RGB), "RGB");
                Assert.Null(cs.GetBaseColorSpace(), "GetBaseColorSpace");
                // not indexed so no color table
                Assert.That(cs.GetColorTable().Length, Is.EqualTo(0), "GetColorTable");
#if NET
                Assert.Null(cs.GetIccProfile(), "GetIccProfile");
#else
                Assert.Null(cs.GetICCProfile(), "GetICCProfile");
#endif
                if (TestRuntime.CheckXcodeVersion(8, 0))
                {
                    // kCGColorSpaceDeviceRGB is not a public constant
                    Assert.That(cs.Name, Is.EqualTo("kCGColorSpaceDeviceRGB"), "Name");
                    Assert.False(cs.IsWideGamutRgb, "IsWideGamutRgb");
                    Assert.True(cs.SupportsOutput, "SupportsOutput");
                    Assert.Null(cs.GetIccData(), "GetIccData");
                }
            }
        }
示例#28
0
        /// <summary>
        /// Converts raw image data from a CMSampleBugger into a CGImage.
        /// </summary>
        /// <returns>The image from sample buffer.</returns>
        /// <param name="sampleBuffer">Sample buffer.</param>
        static CGImage GetImageFromSampleBuffer(CMSampleBuffer sampleBuffer)
        {
            // Get the CoreVideo image
            using (var pixelBuffer = sampleBuffer.GetImageBuffer() as CVPixelBuffer)
            {
                pixelBuffer.Lock(CVPixelBufferLock.None);

                var baseAddress = pixelBuffer.BaseAddress;
                int bytesPerRow = (int)pixelBuffer.BytesPerRow;
                int width       = (int)pixelBuffer.Width;
                int height      = (int)pixelBuffer.Height;
                var flags       = CGBitmapFlags.PremultipliedFirst | CGBitmapFlags.ByteOrder32Little;

                // Create a CGImage on the RGB colorspace from the configured parameter above
                using (var cs = CGColorSpace.CreateDeviceRGB())
                    using (var context = new CGBitmapContext(baseAddress, width, height, 8, bytesPerRow, cs, (CGImageAlphaInfo)flags))
                    {
                        var cgImage = context.ToImage();
                        pixelBuffer.Unlock(CVPixelBufferLock.None);
                        return(cgImage);
                    }
            }
        }
示例#29
0
        public void Present()
        {
            _bitmap.LockPixels();
            IntPtr length;
            var    pixels = _bitmap.GetPixels(out length);

            const int bitmapInfo      = ((int)CGBitmapFlags.ByteOrder32Big) | ((int)CGImageAlphaInfo.PremultipliedLast);
            var       bounds          = GetApplicationFrame();
            var       statusBarOffset = UIScreen.MainScreen.Bounds.Height - bounds.Height;

            using (var colorSpace = CGColorSpace.CreateDeviceRGB())
                using (var bContext = new CGBitmapContext(pixels, _bitmap.Width, _bitmap.Height, 8, _bitmap.Width * 4, colorSpace, (CGImageAlphaInfo)bitmapInfo))
                    using (var image = bContext.ToImage())
                        using (var context = UIGraphics.GetCurrentContext())
                        {
                            // flip the image for CGContext.DrawImage
                            context.TranslateCTM(0, bounds.Height + statusBarOffset);
                            context.ScaleCTM(1, -1);
                            context.DrawImage(bounds, image);
                        }

            _bitmap.UnlockPixels();
        }
        protected override NSImage Transform(NSImage sourceBitmap, string path, ImageSource source, bool isPlaceholder, string key)
        {
            var       colorSpace       = CGColorSpace.CreateDeviceRGB();
            const int bytesPerPixel    = 4;
            int       width            = (int)sourceBitmap.CGImage.Width;
            int       height           = (int)sourceBitmap.CGImage.Height;
            var       bytes            = new byte[width * height * bytesPerPixel];
            int       bytesPerRow      = bytesPerPixel * width;
            const int bitsPerComponent = 8;

            using (var context = new CGBitmapContext(bytes, width, height, bitsPerComponent, bytesPerRow, colorSpace, CGBitmapFlags.PremultipliedLast | CGBitmapFlags.ByteOrder32Big))
            {
                CGRect drawRect = new CGRect(0.0, 0.0, sourceBitmap.Size.Width, sourceBitmap.Size.Height);
                context.SetFillColor(HexColor.ToUIColor().CGColor);
                context.FillRect(drawRect);
                context.DrawImage(drawRect, sourceBitmap.CGImage);

                using (var output = context.ToImage())
                {
                    return(new NSImage(output, CGSize.Empty));
                }
            }
        }