Exemple #1
0
        static UIImage imageWithPDFPage(CGPDFPage page, float scale ,CGAffineTransform t )
        {
            if (page == null)
            {
                return null ;
            }

            RectangleF box = page.GetBoxRect(CGPDFBox.Crop);

            t.Scale(scale,scale);
            box = new RectangleF(box.Location,new SizeF(box.Size.Width * scale, box.Size.Height * scale));

            var pixelWidth = box.Size.Width ;
            CGColorSpace cs = CGColorSpace.CreateDeviceRGB() ;
            //DebugAssert( cs ) ;
            var _buffer = Marshal.AllocHGlobal((int)(box.Width * box.Height));
            UIGraphics.BeginImageContext(box.Size);
            CGContext c = UIGraphics.GetCurrentContext();
            cs.Dispose();
            c.ConcatCTM(t);
            c.DrawPDFPage(page);

            var image = UIGraphics.GetImageFromCurrentImageContext();
            return image ;
        }
Exemple #2
0
        static UIImage imageWithPDFNamed(string name,float scale,CGAffineTransform t)
        {
            CGPDFDocument doc = CreatePDFDocumentWithName(name ) ;
            if ( doc == null)
            {
                return null ;
            }

            // PDF pages are numbered starting at page 1
            CGPDFPage page = doc.GetPage(1);

            var result = imageWithPDFPage(page,scale,t);
            return result ;
        }
Exemple #3
0
        public static void BeginImageContextWithOptions(CGSize size, bool opaque, nfloat scale)
        {
            // Create new image context
            ColorSpace = CGColorSpace.CreateDeviceRGB ();
            Context = new CGBitmapContext (null, (int)size.Width, (int)size.Height, 8, 0, ColorSpace, CGImageAlphaInfo.PremultipliedLast);

            // Flip context vertically
            var flipVertical = new  CGAffineTransform(1,0,0,-1,0,size.Height);
            Context.ConcatCTM (flipVertical);

            // Save previous context
            ImageSize = size;
            PreviousContext = NSGraphicsContext.CurrentContext;
            NSGraphicsContext.CurrentContext = NSGraphicsContext.FromCGContext (Context, true);
        }
		private UIImage InvertedImage(UIImage originalImage)
		{
			// Invert the image by applying an affine transformation
			UIGraphics.BeginImageContext (originalImage.Size);

			// Apply an affine transformation to the original image to generate a vertically flipped image
			CGContext context = UIGraphics.GetCurrentContext ();
			var affineTransformationInvert = new CGAffineTransform(1, 0, 0, -1, 0, originalImage.Size.Height);
			context.ConcatCTM(affineTransformationInvert);
			originalImage.Draw (PointF.Empty);

			UIImage invertedImage = UIGraphics.GetImageFromCurrentImageContext ();
			UIGraphics.EndImageContext ();

			return invertedImage;
		}
Exemple #5
0
        static UIImage[] imagesWithPDFNamed(string name, float scale ,CGAffineTransform t)
        {
            CGPDFDocument doc = CreatePDFDocumentWithName(name ) ;
            List<UIImage> images = new List<UIImage>();

            // PDF pages are numbered starting at page 1
            for( int pageIndex=1; pageIndex <= doc.Pages; ++pageIndex )
            {
                var page = doc.GetPage(pageIndex);
                UIImage image = imageWithPDFPage(page,scale,t);
                if(image != null)
                    images.Add(image);
            }

            return images.ToArray() ;
        }
Exemple #6
0
 public void TranslateTransform(float offsetX, float offsetY)
 {
     Control.TranslateCTM(offsetX, offsetY);
     currentTransform = CGAffineTransform.Multiply(CGAffineTransform.MakeTranslation(offsetX, offsetY), currentTransform);
 }
 void CreateDecompressionSession(AVAssetTrack videoTrack)
 {
     CMFormatDescription[] formatDescriptions = videoTrack.FormatDescriptions;
     var formatDescription = (CMVideoFormatDescription)formatDescriptions [0];
     videoPreferredTransform = videoTrack.PreferredTransform;
     decompressionSession = VTDecompressionSession.Create (DidDecompress, formatDescription);
 }
Exemple #8
0
 public void ScaleTransform(float scaleX, float scaleY)
 {
     Control.ScaleCTM(scaleX, scaleY);
     currentTransform = CGAffineTransform.Multiply(CGAffineTransform.MakeScale(scaleX, scaleY), currentTransform);
 }
        UIImage GetImage(UIColor strokeColor, UIColor fillColor, CGSize size, nfloat scale, bool shouldCrop = true, bool keepAspectRatio = true)
        {
            if (size.Width == 0 || size.Height == 0 || scale <= 0 || strokeColor == null ||
                fillColor == null)
            {
                return(null);
            }

            nfloat uncroppedScale;
            CGRect croppedRectangle = new CGRect();

            CGPoint [] cachedPoints;

            if (shouldCrop && (cachedPoints = Points).Any())
            {
                croppedRectangle         = getCroppedRectangle(cachedPoints);
                croppedRectangle.Width  /= scale;
                croppedRectangle.Height /= scale;
                if (croppedRectangle.X >= 5)
                {
                    croppedRectangle.X     -= 5;
                    croppedRectangle.Width += 5;
                }
                if (croppedRectangle.Y >= 5)
                {
                    croppedRectangle.Y      -= 5;
                    croppedRectangle.Height += 5;
                }
                if (croppedRectangle.X + croppedRectangle.Width <= size.Width - 5)
                {
                    croppedRectangle.Width += 5;
                }
                if (croppedRectangle.Y + croppedRectangle.Height <= size.Height - 5)
                {
                    croppedRectangle.Height += 5;
                }

                nfloat scaleX = croppedRectangle.Width / Bounds.Width;
                nfloat scaleY = croppedRectangle.Height / Bounds.Height;
                uncroppedScale = 1 / (nfloat)Math.Max(scaleX, scaleY);
            }
            else
            {
                uncroppedScale = scale;
            }

            //Make sure the image is scaled to the screen resolution in case of Retina display.
            if (keepAspectRatio)
            {
                UIGraphics.BeginImageContext(size);
            }
            else
            {
                UIGraphics.BeginImageContext(new CGSize(croppedRectangle.Width * uncroppedScale, croppedRectangle.Height * uncroppedScale));
            }

            //Create context and set the desired options
            CGContext context = UIGraphics.GetCurrentContext();

            context.SetFillColor(fillColor.CGColor);
            context.FillRect(new CGRect(0, 0, size.Width, size.Height));
            context.SetStrokeColor(strokeColor.CGColor);
            context.SetLineWidth(StrokeWidth);
            context.SetLineCap(CGLineCap.Round);
            context.SetLineJoin(CGLineJoin.Round);
            context.ScaleCTM(uncroppedScale, uncroppedScale);

            //Obtain all drawn paths from the array
            foreach (var bezierPath in paths)
            {
                var tempPath = (UIBezierPath)bezierPath.Copy();
                if (shouldCrop)
                {
                    tempPath.ApplyTransform(CGAffineTransform.MakeTranslation(-croppedRectangle.X, -croppedRectangle.Y));
                }
                CGPath path = tempPath.CGPath;
                context.AddPath(path);
                tempPath = null;
            }
            context.StrokePath();

            UIImage image = UIGraphics.GetImageFromCurrentImageContext();

            UIGraphics.EndImageContext();

            return(image);
        }
        // https://developer.apple.com/library/mac/#documentation/graphicsimaging/conceptual/drawingwithquartz2d/dq_patterns/dq_patterns.html#//apple_ref/doc/uid/TP30001066-CH206-TPXREF101
        internal override void Setup(Graphics graphics, bool fill)
        {
            // if this is the same as the last that was set then return
            if (graphics.LastBrush == this)
                return;

            // obtain our width and height so we can set the pattern rectangle
            float hatch_width = getHatchWidth (hatchStyle);
            float hatch_height = getHatchHeight (hatchStyle);

            //choose the pattern to be filled based on the currentPattern selected
            var patternSpace = CGColorSpace.CreatePattern(null);
            graphics.context.SetFillColorSpace(patternSpace);
            patternSpace.Dispose();

            // Pattern default work variables
            var patternRect = new CGRect (HALF_PIXEL_X,HALF_PIXEL_Y,hatch_width+HALF_PIXEL_X,hatch_height+HALF_PIXEL_Y);
            var patternTransform = CGAffineTransform.MakeIdentity();

            // Since all the patterns were developed with MonoMac on Mac OS the coordinate system is
            // defaulted to the lower left corner being 0,0 which means for MonoTouch and any view
            // that is flipped we need to flip it again.  Yep should have thought about it to begin with
            // will look into changing it later if need be.
            #if MONOMAC
            if (graphics.isFlipped)
                patternTransform = new CGAffineTransform(1, 0, 0, -1, 0, hatch_height);
            #endif
            #if MONOTOUCH
            if (!graphics.isFlipped)
                patternTransform = new CGAffineTransform(1, 0, 0, -1, 0, hatch_height);
            #endif

            // DrawPattern callback which will be set depending on hatch style
            CGPattern.DrawPattern drawPattern;

            switch (hatchStyle)
            {
            case HatchStyle.Horizontal:
            case HatchStyle.LightHorizontal:
            case HatchStyle.NarrowHorizontal:
            case HatchStyle.DarkHorizontal:
                drawPattern = HatchHorizontal;
                break;
            case HatchStyle.Vertical:
            case HatchStyle.LightVertical:
            case HatchStyle.NarrowVertical:
            case HatchStyle.DarkVertical:
                patternTransform = CGAffineTransform.MakeRotation(90 * (float)Math.PI / 180);
                drawPattern = HatchHorizontal;
                break;
            case HatchStyle.ForwardDiagonal:
            case HatchStyle.LightDownwardDiagonal:
            case HatchStyle.DarkDownwardDiagonal:
            case HatchStyle.WideDownwardDiagonal:
                // We will flip the x-axis here
                patternTransform = CGAffineTransform.MakeScale(-1,1);
                drawPattern = HatchUpwardDiagonal;
                break;
            case HatchStyle.BackwardDiagonal:
            case HatchStyle.LightUpwardDiagonal:
            case HatchStyle.DarkUpwardDiagonal:
            case HatchStyle.WideUpwardDiagonal:
                drawPattern = HatchUpwardDiagonal;
                break;
            case HatchStyle.LargeGrid:
            case HatchStyle.SmallGrid:
            case HatchStyle.DottedGrid:
                drawPattern = HatchGrid;
                break;
            case HatchStyle.DiagonalCross:
                drawPattern = HatchDiagonalCross;
                break;
            case HatchStyle.Percent05:
            case HatchStyle.Percent10:
            case HatchStyle.Percent20:
            case HatchStyle.Percent25:
            case HatchStyle.Percent30:
            case HatchStyle.Percent40:
            case HatchStyle.Percent50:
            case HatchStyle.Percent60:
            case HatchStyle.Percent70:
            case HatchStyle.Percent75:
            case HatchStyle.Percent80:
            case HatchStyle.Percent90:
                drawPattern = HatchPercentage;
                break;
            case HatchStyle.Sphere:
                drawPattern = HatchSphere;
                break;
            case HatchStyle.DashedDownwardDiagonal:
                patternTransform = CGAffineTransform.MakeScale(-1,1);
                drawPattern = HatchDashedDiagonal;
                break;
            case HatchStyle.DashedUpwardDiagonal:
                drawPattern = HatchDashedDiagonal;
                break;
            case HatchStyle.DashedHorizontal:
                drawPattern = HatchDashedHorizontal;
                break;
            case HatchStyle.DashedVertical:
                patternTransform = CGAffineTransform.MakeRotation(-90 * (float)Math.PI / 180);
                drawPattern = HatchDashedHorizontal;
                break;
            case HatchStyle.LargeConfetti:
            case HatchStyle.SmallConfetti:
                drawPattern = HatchConfetti;
                break;
            case HatchStyle.ZigZag:
                drawPattern = HatchZigZag;
                break;
            case HatchStyle.Wave:
                drawPattern = HatchWave;
                break;
            case HatchStyle.HorizontalBrick:
                drawPattern = HatchHorizontalBrick;
                break;
            case HatchStyle.DiagonalBrick:
                drawPattern = HatchDiagonalBrick;
                break;
            //			case HatchStyle.Weave:
            //				drawPattern = HatchWeave;
            //				break;
            case HatchStyle.Trellis:
                drawPattern = HatchTrellis;
                break;
            case HatchStyle.LargeCheckerBoard:
            case HatchStyle.SmallCheckerBoard:
                drawPattern = HatchCheckered;
                break;
            case HatchStyle.OutlinedDiamond:
                drawPattern = HatchOutlinedDiamond;
                break;
            case HatchStyle.SolidDiamond:
                drawPattern = HatchSolidDiamond;
                break;
            case HatchStyle.DottedDiamond:
                drawPattern = HatchDottedDiamond;
                break;
            case HatchStyle.Divot:
                drawPattern = HatchDivot;
                break;
            case HatchStyle.Shingle:
                drawPattern = HatchShingle;
                break;
            case HatchStyle.Plaid:
                drawPattern = HatchPlaid;
                break;
            default:
                drawPattern = DrawPolkaDotPattern;
                break;
            }

            //set the pattern as the Current Context’s fill pattern
            var pattern = new CGPattern(patternRect,
                                    patternTransform,
                                    hatch_width,hatch_height,
                                        CGPatternTiling.NoDistortion,
                                    true, drawPattern);
            //we dont need to set any color, as the pattern cell itself has chosen its own color
            graphics.context.SetFillPattern(pattern, new nfloat[] { 1 });

            graphics.LastBrush = this;
            // I am setting this to be used for Text coloring in DrawString
            graphics.lastBrushColor = foreColor;
        }
        /// <summary>
        /// Draws the specified portion of the specified Image at the specified location and with the specified size.
        /// 
        /// The destPoints specifies a parallelogram with the first point specifying the upper left corner, 
        /// second point specifying the upper right corner and the third point specifying the lower left corner.
        /// 
        /// The srcRect parameter specifies a rectangular portion of the image object to draw. This portion is scaled 
        /// up or down (in the case where source rectangle overruns the bounds of the image) to fit inside the rectangle 
        /// specified by the destRect parameter.  
        /// </summary>
        /// <param name="image">Image.</param>
        /// <param name="destPoints">Destination points.</param>
        /// <param name="srcRect">Source rect.</param>
        /// <param name="srcUnit">Source unit.</param>
        public void DrawImage(Image image, PointF [] destPoints, RectangleF srcRect, GraphicsUnit srcUnit)
        {
            if (image == null)
                throw new ArgumentNullException ("image");
            if (destPoints == null)
                throw new ArgumentNullException ("destPoints");

            if (destPoints.Length < 3)
                throw new ArgumentException ("Destination points must be an array with a length of 3 or 4. " +
                                             "A length of 3 defines a parallelogram with the upper-left, upper-right, " +
                                             "and lower-left corners. A length of 4 defines a quadrilateral with the " +
                                             "fourth element of the array specifying the lower-right coordinate.");

            // Windows throws a Not Implemented error if the points are more than 3
            if (destPoints.Length > 3)
                throw new NotImplementedException ();

            var srcRect1 = srcRect;

            // If the source units are not the same we need to convert them
            // The reason we check for Pixel here is that our graphics already has the Pixel's baked into the model view transform
            if (srcUnit != graphicsUnit && srcUnit != GraphicsUnit.Pixel)
            {
                ConversionHelpers.GraphicsUnitConversion (srcUnit, graphicsUnit, image.HorizontalResolution, image.VerticalResolution,  ref srcRect1);
            }

            // Obtain the subImage
            var subImage = image.NativeCGImage.WithImageInRect (srcRect1.ToCGRect ());

            // If we do not have anything to draw then we exit here
            if (subImage.Width == 0 || subImage.Height == 0)
                return;

            // create our rectangle.  Offset is 0 because the CreateGeometricTransform bakes our x,y offset in there.
            var rect = new RectangleF (0,0, destPoints [1].X - destPoints [0].X, destPoints [2].Y - destPoints [0].Y);

            // We need to flip our Y axis so the image appears right side up
            var geoTransform = new CGAffineTransform (1, 0, 0, -1, 0, rect.Height);

            // Make sure we scale the image in case the source rectangle
            // overruns our subimage bounds (width and/or height)
            float scaleX = subImage.Width/srcRect1.Width;
            float scaleY = subImage.Height/srcRect1.Height;
            geoTransform.Scale (scaleX, scaleY);

            //var geott = GeomUtilities.CreateGeometricTransform (rect, destPoints);
            geoTransform.Multiply (GeomUtilities.CreateGeometricTransform (rect, destPoints));

            // Apply our transform to the context
            context.ConcatCTM (geoTransform);

            // now we draw our image.
            context.DrawImage(rect.ToCGRect (), subImage);

            // Now we revert our image transform from the context
            var revert = CGAffineTransform.CGAffineTransformInvert (geoTransform);
            context.ConcatCTM (revert);
        }
        internal static void NativeDrawString(CGBitmapContext bitmapContext, string s, CTFont font, CCColor4B brush, RectangleF layoutRectangle)
        {
            if (font == null)
            {
                throw new ArgumentNullException("font");
            }

            if (s == null || s.Length == 0)
            {
                return;
            }

            bitmapContext.ConcatCTM(bitmapContext.GetCTM().Invert());

            // This is not needed here since the color is set in the attributed string.
            //bitmapContext.SetFillColor(brush.R/255f, brush.G/255f, brush.B/255f, brush.A/255f);

            // I think we only Fill the text with no Stroke surrounding
            //bitmapContext.SetTextDrawingMode(CGTextDrawingMode.Fill);

            var attributedString = buildAttributedString(s, font, brush);

            // Work out the geometry
            RectangleF insetBounds = layoutRectangle;

            PointF textPosition = new PointF(insetBounds.X,
                                             insetBounds.Y);

            float boundsWidth = insetBounds.Width;

            // Calculate the lines
            int start  = 0;
            int length = attributedString.Length;

            var typesetter = new CTTypesetter(attributedString);

            float baselineOffset = 0;

            // First we need to calculate the offset for Vertical Alignment if we
            // are using anything but Top
            if (vertical != CCVerticalTextAlignment.Top)
            {
                while (start < length)
                {
                    int count = typesetter.SuggestLineBreak(start, boundsWidth);
                    var line  = typesetter.GetLine(new NSRange(start, count));

                    // Create and initialize some values from the bounds.
                    float ascent;
                    float descent;
                    float leading;
                    line.GetTypographicBounds(out ascent, out descent, out leading);
                    baselineOffset += (float)Math.Ceiling(ascent + descent + leading + 1);                      // +1 matches best to CTFramesetter's behavior
                    line.Dispose();
                    start += count;
                }
            }

            start = 0;

            while (start < length && textPosition.Y < insetBounds.Bottom)
            {
                // Now we ask the typesetter to break off a line for us.
                // This also will take into account line feeds embedded in the text.
                //  Example: "This is text \n with a line feed embedded inside it"
                int count = typesetter.SuggestLineBreak(start, boundsWidth);
                var line  = typesetter.GetLine(new NSRange(start, count));

                // Create and initialize some values from the bounds.
                float ascent;
                float descent;
                float leading;
                line.GetTypographicBounds(out ascent, out descent, out leading);

                // Calculate the string format if need be
                var penFlushness = 0.0f;

                if (horizontal == CCTextAlignment.Right)
                {
                    penFlushness = (float)line.GetPenOffsetForFlush(1.0f, boundsWidth);
                }
                else if (horizontal == CCTextAlignment.Center)
                {
                    penFlushness = (float)line.GetPenOffsetForFlush(0.5f, boundsWidth);
                }

                // initialize our Text Matrix or we could get trash in here
                var textMatrix = CGAffineTransform.MakeIdentity();

                if (vertical == CCVerticalTextAlignment.Top)
                {
                    textMatrix.Translate(penFlushness, insetBounds.Height - textPosition.Y - (float)Math.Floor(ascent - 1));
                }
                if (vertical == CCVerticalTextAlignment.Center)
                {
                    textMatrix.Translate(penFlushness, ((insetBounds.Height / 2) + (baselineOffset / 2)) - textPosition.Y - (float)Math.Floor(ascent - 1));
                }
                if (vertical == CCVerticalTextAlignment.Bottom)
                {
                    textMatrix.Translate(penFlushness, baselineOffset - textPosition.Y - (float)Math.Floor(ascent - 1));
                }

                // Set our matrix
                bitmapContext.TextMatrix = textMatrix;

                // and draw the line
                line.Draw(bitmapContext);

                // Move the index beyond the line break.
                start          += count;
                textPosition.Y += (float)Math.Ceiling(ascent + descent + leading + 1);                 // +1 matches best to CTFramesetter's behavior
                line.Dispose();
            }
        }
        private void InitWithCGImage(CGImage image)
        {
            int	width, height;
            CGBitmapContext bitmap = null;
            bool hasAlpha;
            CGImageAlphaInfo alphaInfo;
            CGColorSpace colorSpace;
            int bitsPerComponent, bytesPerRow;
            CGBitmapFlags bitmapInfo;
            bool premultiplied = false;
            int bitsPerPixel = 0;

            if (image == null) {
                throw new ArgumentException (" image is invalid! " );
            }

            alphaInfo = image.AlphaInfo;
            hasAlpha = ((alphaInfo == CGImageAlphaInfo.PremultipliedLast) || (alphaInfo == CGImageAlphaInfo.PremultipliedFirst) || (alphaInfo == CGImageAlphaInfo.Last) || (alphaInfo == CGImageAlphaInfo.First) ? true : false);

            imageSize.Width = (int)image.Width;
            imageSize.Height = (int)image.Height;

            width = (int)image.Width;
            height = (int)image.Height;

            // Not sure yet if we need to keep the original image information
            // before we change it internally.  TODO look at what windows does
            // and follow that.
            bitmapInfo = image.BitmapInfo;
            bitsPerComponent = (int)image.BitsPerComponent;
            bitsPerPixel = (int)image.BitsPerPixel;
            bytesPerRow = width * bitsPerPixel/bitsPerComponent;
            int size = bytesPerRow * height;

            colorSpace = image.ColorSpace;

            // Right now internally we represent the images all the same
            // I left the call here just in case we find that this is not
            // possible.  Read the comments for non alpha images.
            if(colorSpace != null) {
                if( hasAlpha ) {
                    premultiplied = true;
                    colorSpace = CGColorSpace.CreateDeviceRGB ();
                    bitsPerComponent = 8;
                    bitsPerPixel = 32;
                    bitmapInfo = CGBitmapFlags.PremultipliedLast;
                }
                else
                {
                    // even for images without alpha we will internally
                    // represent them as RGB with alpha.  There were problems
                    // if we do not do it this way and creating a bitmap context.
                    // The images were not drawing correctly and tearing.  Also
                    // creating a Graphics to draw on was a nightmare.  This
                    // should probably be looked into or maybe it is ok and we
                    // can continue representing internally with this representation
                    premultiplied = true;
                    colorSpace = CGColorSpace.CreateDeviceRGB ();
                    bitsPerComponent = 8;
                    bitsPerPixel = 32;
                    bitmapInfo = CGBitmapFlags.NoneSkipLast;
                }
            } else {
                premultiplied = true;
                colorSpace = CGColorSpace.CreateDeviceRGB ();
                bitsPerComponent = 8;
                bitsPerPixel = 32;
                bitmapInfo = CGBitmapFlags.NoneSkipLast;
            }

            bytesPerRow = width * bitsPerPixel/bitsPerComponent;
            size = bytesPerRow * height;

            bitmapBlock = Marshal.AllocHGlobal (size);
            bitmap = new CGBitmapContext (bitmapBlock,
                                          width, height,
                                          bitsPerComponent,
                                          bytesPerRow,
                                          colorSpace,
                                          bitmapInfo);

            bitmap.ClearRect (new CGRect (0,0,width,height));

            // We need to flip the Y axis to go from right handed to lefted handed coordinate system
            var transform = new CGAffineTransform(1, 0, 0, -1, 0, image.Height);
            bitmap.ConcatCTM(transform);

            bitmap.DrawImage (new CGRect (0, 0, image.Width, image.Height), image);

            var provider = new CGDataProvider (bitmapBlock, size, true);
            NativeCGImage = new CGImage (width, height, bitsPerComponent,
                                         bitsPerPixel, bytesPerRow,
                                         colorSpace,
                                         bitmapInfo,
                                         provider, null, true, image.RenderingIntent);

            colorSpace.Dispose();
            bitmap.Dispose();
        }
Exemple #14
0
 public Matrix()
 {
     transform = CGAffineTransform.MakeIdentity();
 }
Exemple #15
0
 internal Matrix(CGAffineTransform transform)
 {
     this.transform = transform;
 }
Exemple #16
0
 public void Reset()
 {
     transform = CGAffineTransform.MakeIdentity();
 }
Exemple #17
0
 public void Invert()
 {
     transform = transform.Invert();
 }
Exemple #18
0
 public Matrix(float m11, float m12, float m21, float m22, float dx, float dy)
 {
     transform = new CGAffineTransform(m11, m12, m21, m22, dx, dy);
 }
        public override void TouchesMoved(NSSet touches, UIEvent evt)
        {
            // base.TouchesMoved(touches, evt);

            if (!TrapState.Shared.HasActiveSnapshotImage) return;

            touchesDidMove = true;

            var touch = touches.AnyObject as UITouch;

            var point = touch.LocationInView(bufferImageView);

            var difX = point.X - pathStart.X;
            var difY = point.Y - pathStart.Y;

            var path = new UIBezierPath ();

            switch (Tool) {
            case Annotate.Tool.Callout:
            case Annotate.Tool.Color:

                return;

            case Annotate.Tool.Marker:

                counter++;

                markerPoints[counter] = point;

                if (counter == 4) {

                    // move the endpoint to the middle of the line joining the second control point
                    // of the first Bezier segment and the first control point of the second Bezier segment
                    markerPoints[3] = new CGPoint ((markerPoints[2].X + markerPoints[4].X) / 2, (markerPoints[2].Y + markerPoints[4].Y) / 2);

                    path = new UIBezierPath ();

                    path.MoveTo(markerPoints[0]);

                    path.AddCurveToPoint(markerPoints[3], markerPoints[1], markerPoints[2]);

                    path.LineWidth = bzPath.LineWidth;

                    // add to cached path to draw and add to undo stack
                    bzPath.AppendPath(path);

                    // replace points and get ready to handle the next segment
                    markerPoints[0] = markerPoints[3];
                    markerPoints[1] = markerPoints[4];

                    counter = 1;
                }

                path.Stroke();
                bufferImageView.Image = UIGraphics.GetImageFromCurrentImageContext();

                break;
            case Annotate.Tool.Arrow:

                var total = Math.Sqrt(Math.Pow(difX, 2) + Math.Pow(difX, 2));

                var tailL = (nfloat)(total * 0.7);

                var tailW = bzPath.LineWidth / 2;

                var headW = (nfloat)((total * 0.2) / 2);

                arrowPoints[0] = new CGPoint (0, tailW);
                arrowPoints[1] = new CGPoint (tailL, tailW);
                arrowPoints[2] = new CGPoint (tailL, headW);
                arrowPoints[3] = new CGPoint ((nfloat)total, 0);
                arrowPoints[4] = new CGPoint (tailL, -headW);
                arrowPoints[5] = new CGPoint (tailL, -tailW);
                arrowPoints[6] = new CGPoint (0, -tailW);

                nfloat cosine = (nfloat)(difX / total), sine = (nfloat)(difY / total);

                var transform = new CGAffineTransform (cosine, sine, -sine, cosine, pathStart.X, pathStart.Y);

                var cgPath = new CGPath ();

                cgPath.AddLines(transform, arrowPoints, 7);

                cgPath.CloseSubpath();

                path = UIBezierPath.FromPath(cgPath);

                path.LineWidth = bzPath.LineWidth;

                // cache path to draw and add to undo stack later
                bzPath = path;

                UIGraphics.BeginImageContextWithOptions(bufferRect.Size, false, 0);

                strokeColor.SetFill();
                path.Fill();

                strokeColor.SetStroke();
                path.Stroke();

                bufferImageView.Image = UIGraphics.GetImageFromCurrentImageContext();

                UIGraphics.EndImageContext();

                break;
            case Annotate.Tool.Circle:
            case Annotate.Tool.Square:

                var origin = new CGPoint ((nfloat)Math.Min(pathStart.X, point.X), (nfloat)Math.Min(pathStart.Y, point.Y));

                var size = new CGSize ((nfloat)Math.Abs(difX), (nfloat)Math.Abs(difY));

                var rect = new CGRect (origin, size);

                path = Tool == Annotate.Tool.Circle ? UIBezierPath.FromOval(rect) : UIBezierPath.FromRect(rect);

                path.LineWidth = bzPath.LineWidth;

                // cache path to draw and add to undo stack later
                bzPath = path;

                UIGraphics.BeginImageContextWithOptions(bufferRect.Size, false, 0);

                strokeColor.SetStroke();

                path.Stroke();

                bufferImageView.Image = UIGraphics.GetImageFromCurrentImageContext();

                UIGraphics.EndImageContext();

                break;
            }
        }
        public void Translate(float dx, float dy)
        {
            var translateMatrix = new Matrix(CGAffineTransform.MakeTranslation(dx, dy));

            Transform(translateMatrix);
        }
        public void StartTvOut()
        {
            if (UIApplication.SharedApplication.KeyWindow == null)
                return;

            var screens = UIScreen.Screens;
            if (screens.Count() <= 1) {
                Console.WriteLine("TVOutManager: startTVOut failed (no external screens detected)");
                return;
            }

            if (tvoutWindow != null)
                tvoutWindow.Dispose();
                tvoutWindow = null;

            if (tvoutWindow == null) {
                deviceWindow = UIApplication.SharedApplication.KeyWindow;

                SizeF max = new SizeF();
                max.Width = 0;
                max.Height = 0;
                UIScreenMode maxScreenMode = null;
                UIScreen external = UIScreen.Screens[1];

                for (int i = 0; i < external.AvailableModes.Count(); i++) {

                    UIScreenMode current = UIScreen.Screens[1].AvailableModes[i];
                    if (current.Size.Width > max.Width) {
                        max = current.Size;
                        maxScreenMode = current;
                    }
                }

                external.CurrentMode = maxScreenMode;
                tvoutWindow = new UIWindow(new RectangleF(0, 0, max.Width, max.Height));
                tvoutWindow.UserInteractionEnabled = false;
                tvoutWindow.Screen = external;

                // size the mirrorView to expand to fit the external screen
                var mirrorRect = UIScreen.MainScreen.Bounds;
                var horiz = max.Width / mirrorRect.Width;
                var vert = max.Height / mirrorRect.Height;

                var bigScale = horiz < vert ? horiz : vert;
                mirrorRect = new RectangleF(mirrorRect.X, mirrorRect.Y, mirrorRect.Size.Width * bigScale, mirrorRect.Size.Height * bigScale);

                mirrorView = new UIImageView(mirrorRect);
                mirrorView.Center = tvoutWindow.Center;

                // TV safe area -- scale the window by 20% -- for composite / component, not needed for VGA output
                if (tvSafeMode) tvoutWindow.Transform = CGAffineTransform.MakeScale(.8f, .8f);
                tvoutWindow.AddSubview(mirrorView);
                tvoutWindow.MakeKeyAndVisible();
                tvoutWindow.Hidden = false;
                tvoutWindow.BackgroundColor = UIColor.DarkGray;

                //orient the view properly
                if (UIDevice.CurrentDevice.Orientation == UIDeviceOrientation.LandscapeLeft) {
                    mirrorView.Transform = CGAffineTransform.MakeRotation((float)Math.PI * 1.5f);
                } else if (UIDevice.CurrentDevice.Orientation == UIDeviceOrientation.LandscapeRight) {
                    mirrorView.Transform = CGAffineTransform.MakeRotation((float)Math.PI * -1.5f);
                }

                startingTransform = mirrorView.Transform;
                deviceWindow.MakeKeyAndVisible();
                this.UpdateTvOut();

                if (kUseBackgroundThread){
                    new Thread(UpdateLoop).Start();
                    }
                else{
                    updateTimer = NSTimer.CreateScheduledTimer(1.0/kFPS,this,new Selector("UpdateTvOut:"),null, true );
                }

            }
        }
        void TouchesMovedWithEvent(NSSet touches, UIEvent theEvent)
        {
            if (touches.Count == 1)
            {
                this.TouchCount++;
                if (this.TouchCount == 3)
                {
                    if (Math.Abs(this.Center.X - this.OriginalCenter.X) > Math.Abs(this.Center.Y - this.OriginalCenter.Y)) this.MoveLaterally = true;
                    else this.MoveLaterally = false;

                    this.FirstEdgeHit = true;
                }

                UITouch touch = touches.AllObjects().FirstObject();
                CGPoint center = this.Center;
                CGPoint currentLoc = touch.LocationInView(this);
                CGPoint prevLoc = touch.PreviousLocationInView(this);
                if (this.TouchCount < 3)
                {
                    center.X += (currentLoc.X - prevLoc.X);
                    center.Y += (currentLoc.Y - prevLoc.Y);
                }
                else
                {
                    if (this.MoveLaterally)
                    {
                        if (currentLoc.X - prevLoc.X < 0.0f && !this.AllowLeft) return;
                        else if (currentLoc.X - prevLoc.X > 0.0f && !this.AllowRight) return;

                        center.X += (currentLoc.X - prevLoc.X);
                    }
                    else
                    {
                        if (currentLoc.Y - prevLoc.Y < 0.0f && !this.AllowUp) return;
                        else if (currentLoc.Y - prevLoc.Y > 0.0f && !this.AllowDown) return;

                        center.Y += (currentLoc.Y - prevLoc.Y);
                    }

                }

                this.Center = center;
                if (this.MoveLaterally)
                {
                    if ((this.Center.X + this.Frame.Size.Width / 2) > this.Superview.Frame.Size.Width)
                    {
                        this._resetRotation(KSDirection.Right);
                        this.LastDirection = KSDirection.Right;
                        if (this.FirstEdgeHit)
                        {
                            this.FirstEdgeHit = false;
                            this.Shift = new CGPoint(0, 0);
                        }

                        this.Shift.X += (currentLoc.X - prevLoc.X);
                        this._changeViewOpacityForDirection(KSDirection.Right);
                        if (s_hasRightOverlay)
                        {
                            this._showOverlayWithDirectionCurrentLocationPreviousLocation(KSDirection.Right, currentLoc, prevLoc);
                            return;
                        }

                        this.Transform = CGAffineTransform.MakeRotation(Constants.KRotationFactor * this.Shift.X * Math.PI / 180);
                    }
                    else if ((this.Center.X - this.Frame.Size.Width / 2) < 0)
                    {
                        this._resetRotation(KSDirection.Left);
                        this.LastDirection = KSDirection.Left;
                        if (this.FirstEdgeHit)
                        {
                            this.FirstEdgeHit = false;
                            this.Shift = new CGPoint(0, 0);
                        }

                        this.Shift.X += (currentLoc.X - prevLoc.X);
                        this._changeViewOpacityForDirection(KSDirection.Left);
                        if (s_hasLeftOverlay)
                        {
                            this._showOverlayWithDirectionCurrentLocationPreviousLocation(KSDirection.Left, currentLoc, prevLoc);
                            return;
                        }

                        this.Transform = CGAffineTransform.MakeRotation(Constants.KRotationFactor * this.Shift.X * Math.PI / 180);
                    }
                    else
                    {
                        this.Transform = CGAffineTransform.MakeRotation(0);
                        this.Layer.Opacity = 1.0f;
                        this._hideViewOverlays();
                    }

                }
                else
                {
                    if ((this.Center.Y + this.Frame.Size.Height / 2) > this.Superview.Frame.Size.Height)
                    {
                        if (this.FirstEdgeHit)
                        {
                            this.FirstEdgeHit = false;
                            this.Shift = new CGPoint(0, 0);
                        }

                        this.Shift.Y += (currentLoc.Y - prevLoc.Y);
                        this._changeViewOpacityForDirection(KSDirection.Down);
                        this._showOverlayWithDirectionCurrentLocationPreviousLocation(KSDirection.Down, currentLoc, prevLoc);
                    }
                    else if ((this.Center.Y - this.Frame.Size.Height / 2) < 0)
                    {
                        if (this.FirstEdgeHit)
                        {
                            this.FirstEdgeHit = false;
                            this.Shift = new CGPoint(0, 0);
                        }

                        this.Shift.Y += (currentLoc.Y - prevLoc.Y);
                        this._changeViewOpacityForDirection(KSDirection.Up);
                        this._showOverlayWithDirectionCurrentLocationPreviousLocation(KSDirection.Up, currentLoc, prevLoc);
                    }
                    else
                    {
                        this._hideViewOverlays();
                    }

                }

            }

        }
        internal void RotateFlip(RotateFlipType rotateFlipType)
        {
            CGAffineTransform rotateFlip = CGAffineTransform.MakeIdentity();

            int width, height;
            width = (int)NativeCGImage.Width;
            height = (int)NativeCGImage.Height;

            switch (rotateFlipType)
            {
                //			case RotateFlipType.RotateNoneFlipNone:
                //			//case RotateFlipType.Rotate180FlipXY:
                //				rotateFlip = GeomUtilities.CreateRotateFlipTransform (b.Width, b.Height, 0, false, false);
                //				break;
                case RotateFlipType.Rotate90FlipNone:
                //case RotateFlipType.Rotate270FlipXY:
                rotateFlip = GeomUtilities.CreateRotateFlipTransform (ref width, ref height, 90, false, false);
                break;
                case RotateFlipType.Rotate180FlipNone:
                //case RotateFlipType.RotateNoneFlipXY:
                rotateFlip = GeomUtilities.CreateRotateFlipTransform (ref width, ref height, 0, true, true);
                break;
                case RotateFlipType.Rotate270FlipNone:
                //case RotateFlipType.Rotate90FlipXY:
                rotateFlip = GeomUtilities.CreateRotateFlipTransform (ref width, ref height, 270, false, false);
                break;
                case RotateFlipType.RotateNoneFlipX:
                //case RotateFlipType.Rotate180FlipY:
                rotateFlip = GeomUtilities.CreateRotateFlipTransform (ref width, ref height, 0, true, false);
                break;
                case RotateFlipType.Rotate90FlipX:
                //case RotateFlipType.Rotate270FlipY:
                rotateFlip = GeomUtilities.CreateRotateFlipTransform (ref width, ref height, 90, true, false);
                break;
                case RotateFlipType.Rotate180FlipX:
                //case RotateFlipType.RotateNoneFlipY:
                rotateFlip = GeomUtilities.CreateRotateFlipTransform (ref width, ref height, 0, false, true);
                break;
                case RotateFlipType.Rotate270FlipX:
                //case RotateFlipType.Rotate90FlipY:
                rotateFlip = GeomUtilities.CreateRotateFlipTransform (ref width, ref height, 270, true, false);
                break;
            }

            var format = GetBestSupportedFormat (pixelFormat);
            var bitmapContext = CreateCompatibleBitmapContext (width, height, format);

            bitmapContext.ConcatCTM (rotateFlip);

            bitmapContext.DrawImage (new CGRect (0, 0, NativeCGImage.Width, NativeCGImage.Height), NativeCGImage);

            int size = (int)(bitmapContext.BytesPerRow * bitmapContext.Height);
            var provider = new CGDataProvider (bitmapContext.Data, size, true);

            // If the width or height is not the seme we need to switch the dpiHeight and dpiWidth
            // We should be able to get around this with set resolution later.
            if (NativeCGImage.Width != width || NativeCGImage.Height != height)
            {
                var temp = dpiWidth;
                dpiHeight = dpiWidth;
                dpiWidth = temp;
            }

            NativeCGImage = new CGImage ((int)bitmapContext.Width, (int)bitmapContext.Height, (int)bitmapContext.BitsPerComponent,
                                         (int)bitmapContext.BitsPerPixel, (int)bitmapContext.BytesPerRow,
                                         bitmapContext.ColorSpace,
                                         bitmapContext.AlphaInfo,
                                         provider, null, true, CGColorRenderingIntent.Default);

            physicalDimension.Width = (float)width;
            physicalDimension.Height = (float)height;

            physicalSize = new SizeF (physicalDimension.Width, physicalDimension.Height);
            physicalSize.Width *= ConversionHelpers.MS_DPI / dpiWidth;
            physicalSize.Height *= ConversionHelpers.MS_DPI / dpiHeight;

            // In windows the RawFormat is changed to MemoryBmp to show that the image has changed.
            rawFormat = ImageFormat.MemoryBmp;

            // Set our transform for this image for the new height
            imageTransform = new CGAffineTransform(1, 0, 0, -1, 0, height);
        }
Exemple #24
0
        public static string StringFromGlyphs(PSPDFGlyph[] glyphs, CGAffineTransform t, RectangleF boundingBox)
        {
            var objs = new List<NSObject> ();

            foreach (var glyph in glyphs)
                objs.Add (glyph);

            var arry = NSArray.FromNSObjects (objs.ToArray ());

            var str = Runtime.GetNSObject<NSString> (_StringFromGlyphs (arry.Handle));
            return (string)str;
        }
Exemple #25
0
        private CGAffineTransform NodeToParentTransform()
        {
            if (_isTransformDirty) {
                _transform = CGAffineTransform.MakeIdentity();

                if (!IsRelativeAnchorPoint) {
                    _transform.Translate(TransformAnchor.X, TransformAnchor.Y);
                }

                _transform.Translate((int)Position.X, (int)Position.Y);
                _transform.Rotate(Rotation.ToRadians());
                _transform.Scale(ScaleX, ScaleY);
                _transform.Translate(-TransformAnchor.X, -TransformAnchor.Y);

                _isTransformDirty = false;
            }

            return _transform;
        }
Exemple #26
0
        void SetDownloadTypeButtonDisplay()
        {
            DownloadsNavOutNowBtn.Alpha     = selectedSegmentBtn.Equals(0) ? 1f : 0.4f;
            DownloadsNavOutNowBtn.Transform = selectedSegmentBtn.Equals(0) ?
                                              CGAffineTransform.MakeScale(1f, 1f) : CGAffineTransform.MakeScale(0.75f, 0.75f);


            DownloadsNavUpcomingBtn.Alpha     = selectedSegmentBtn.Equals(1) ? 1f : 0.4f;
            DownloadsNavUpcomingBtn.Transform = selectedSegmentBtn.Equals(1) ?
                                                CGAffineTransform.MakeScale(1f, 1f) : CGAffineTransform.MakeScale(0.75f, 0.75f);
        }
        public void _rubberBand()
        {
            CGPoint cardCenter = this.Center;
            bool isNegative = true;
            bool isVertical = true;
            if (!this.MoveLaterally)
            {
                if (Math.Abs(cardCenter.Y - this.OriginalCenter.Y) > Math.Abs(cardCenter.X - this.OriginalCenter.X))
                {
                    if (cardCenter.Y < this.OriginalCenter.Y)
                    {
                        isNegative = false;
                        isVertical = true;
                    }
                    else
                    {
                        isNegative = true;
                        isVertical = true;
                    }

                }

            }
            else
            {
                if (cardCenter.X < this.OriginalCenter.X)
                {
                    isNegative = false;
                    isVertical = false;
                }
                else
                {
                    isNegative = true;
                    isVertical = false;
                }

            }

            UIView.Animate(Constants.KRubberBandDuration / 3.0f, 0.0f, UIViewAnimationCurve.EaseInOut, () =>
                {
                    CGPoint center = this.OriginalCenter;
                    if (!isNegative && isVertical) center.Y += Constants.KRubberBandFirstPass;
                    else if (isNegative && isVertical) center.Y -= Constants.KRubberBandFirstPass;
                    else if (!isNegative && !isVertical) center.X += Constants.KRubberBandFirstPass;
                    else if (isNegative && !isVertical) center.X -= Constants.KRubberBandFirstPass;

                    this.Center = center;
                    this.Layer.Opacity = 1.0f;
                    this.Transform = CGAffineTransform.MakeRotation(0);
                    this._hideViewOverlays();
                }, (bool finished) =>
                {
                    UIView.Animate(Constants.KRubberBandDuration / 3.0f, () =>
                        {
                            CGPoint center = this.OriginalCenter;
                            if (!isNegative && isVertical) center.Y -= Constants.KRubberBandSecondPass;
                            else if (isNegative && isVertical) center.Y += Constants.KRubberBandSecondPass;
                            else if (!isNegative && !isVertical) center.X -= Constants.KRubberBandSecondPass;
                            else if (isNegative && !isVertical) center.X += Constants.KRubberBandSecondPass;

                            this.Center = center;
                        }, (bool finished2) =>
                        {
                            UIView.Animate(Constants.KRubberBandDuration / 3.0f, () =>
                                {
                                    this.Center = this.OriginalCenter;
                                });
                        });
                });
        }
Exemple #28
0
 public void RotateTransform(float angle)
 {
     angle = (float)CGConversions.DegreesToRadians(angle);
     Control.RotateCTM(angle);
     currentTransform = CGAffineTransform.Multiply(CGAffineTransform.MakeRotation(angle), currentTransform);
 }
 private static extern RectangleF _BoundingBoxFromGlyphs(IntPtr glyphs, CGAffineTransform t);
Exemple #30
0
        public override void AnimateTransition(IUIViewControllerContextTransitioning transitionContext)
        {
            var containerView = transitionContext.ContainerView;

            var fromViewController = transitionContext.GetViewControllerForKey(UITransitionContext.FromViewControllerKey);
            var toViewController   = transitionContext.GetViewControllerForKey(UITransitionContext.ToViewControllerKey);

            toViewController.View.Frame = fromViewController.View.Frame;

            if (IsPresenting)
            {
                var presentedControllerView = toViewController.View;
                var originalCenter          = presentedControllerView.Center;

                var originalSize = presentedControllerView.Frame.Size;

                _square.Frame           = StartingFrame;       //CreateFrameForBubble(originalSize, AnimationHelper.GetCenterPointFromFrame(StartingFrame));
                _square.Center          = AnimationHelper.GetCenterPointFromFrame(StartingFrame);
                _square.Transform       = CGAffineTransform.MakeScale(0.001f, 0.001f);
                _square.BackgroundColor = UIColor.LightGray;

                containerView.AddSubview(_square);

                presentedControllerView.Center    = AnimationHelper.GetCenterPointFromFrame(StartingFrame);
                presentedControllerView.Transform = CGAffineTransform.MakeScale(0.001f, 0.001f);
                presentedControllerView.Alpha     = 0f;

                containerView.AddSubview(toViewController.View);

                UIView.Animate(Duration, 0, UIViewAnimationOptions.CurveEaseOut,
                               () =>
                {
                    _square.Transform = CGAffineTransform.MakeIdentity();
                    presentedControllerView.Transform = CGAffineTransform.MakeIdentity();
                    presentedControllerView.Alpha     = 1f;
                    presentedControllerView.Center    = originalCenter;
                }, () =>
                {
                    transitionContext.CompleteTransition(true);
                }
                               );
            }
            else
            {
                var returningControllerView = fromViewController.View;
                var originalSize            = returningControllerView.Frame.Size;

                _square.Frame  = CreateFrameForBubble(originalSize, AnimationHelper.GetCenterPointFromFrame(StartingFrame));
                _square.Center = AnimationHelper.GetCenterPointFromFrame(StartingFrame);

                containerView.AddSubview(toViewController.View);
                containerView.AddSubview(_square);

                UIView.Animate(Duration, 0, UIViewAnimationOptions.CurveEaseInOut,
                               () =>
                {
                    _square.Transform = CGAffineTransform.MakeScale(0.001f, 0.001f);

                    returningControllerView.Transform = CGAffineTransform.MakeScale(0.001f, 0.001f);
                    returningControllerView.Center    = AnimationHelper.GetCenterPointFromFrame(StartingFrame);
                    returningControllerView.Alpha     = 0f;
                }, () =>
                {
                    returningControllerView.Center = AnimationHelper.GetCenterPointFromFrame(StartingFrame);
                    _square.RemoveFromSuperview();

                    transitionContext.CompleteTransition(true);
                }
                               );
            }
        }
        public static CGRect[] RectsFromGlyphs(PSPDFGlyph [] glyphs, CGAffineTransform t, CGRect boundingBox)
        {
            if (glyphs == null)
                return _RectsFromGlyphs (IntPtr.Zero, t, boundingBox);

            var objs = new List<NSObject>();

            foreach (var glyph in glyphs)
                objs.Add(glyph);

            NSArray arry = NSArray.FromNSObjects(objs.ToArray());
            return _RectsFromGlyphs (arry.Handle, t, boundingBox);
        }
        public virtual UIImage LoadImage(out CGAffineTransform transform, out NSError error)
        {
            unsafe {
                IntPtr val;
                IntPtr val_addr = (IntPtr) ((IntPtr *) &val);

                UIImage ret = LoadImage (out transform, val_addr);
                error = (NSError) Runtime.GetNSObject (val);

                return ret;
            }
        }
        public void HandlePresentMenuPan(UIPanGestureRecognizer pan)
        {
            // how much distance have we panned in reference to the parent view?
            var view = viewControllerForPresentedMenu != null ? viewControllerForPresentedMenu?.View : pan.View;

            if (view == null)
            {
                return;
            }

            var transform = view.Transform;

            view.Transform = CoreGraphics.CGAffineTransform.MakeIdentity();
            var translation = pan.TranslationInView(pan.View);

            view.Transform = transform;

            // do some math to translate this to a percentage based value
            if (!interactive)
            {
                if (translation.X == 0)
                {
                    return; // not sure which way the user is swiping yet, so do nothing
                }

                if (!(pan is UIScreenEdgePanGestureRecognizer))
                {
                    this.PresentDirection = translation.X > 0 ? UIRectEdge.Left : UIRectEdge.Right;
                }

                var menuViewController = this.PresentDirection == UIRectEdge.Left
                    ? SideMenuManager.LeftNavigationController
                    : SideMenuManager.RightNavigationController;
                if (menuViewController != null && visibleViewController != null)
                {
                    interactive = true;
                    visibleViewController.PresentViewController(menuViewController, true, null);
                }
            }

            var direction = this.PresentDirection == UIRectEdge.Left ? 1 : -1;
            var distance  = translation.X / SideMenuManager.MenuWidth;

            // now lets deal with different states that the gesture recognizer sends
            switch (pan.State)
            {
            case UIGestureRecognizerState.Began:
            case UIGestureRecognizerState.Changed:
                if (pan is UIScreenEdgePanGestureRecognizer)
                {
                    this.UpdateInteractiveTransition((float)Math.Min(distance * direction, 1));
                }
                else if (distance > 0 && this.PresentDirection == UIRectEdge.Right && SideMenuManager.LeftNavigationController != null)
                {
                    this.PresentDirection = UIRectEdge.Left;
                    switchMenus           = true;
                    this.CancelInteractiveTransition();
                }
                else if (distance < 0 && this.PresentDirection == UIRectEdge.Left && SideMenuManager.RightNavigationController != null)
                {
                    this.PresentDirection = UIRectEdge.Right;
                    switchMenus           = true;
                    this.CancelInteractiveTransition();
                }
                else
                {
                    this.UpdateInteractiveTransition((float)Math.Min(distance * direction, 1));
                }
                break;

            default:
                interactive    = false;
                view.Transform = CGAffineTransform.MakeIdentity();
                var velocity = pan.VelocityInView(pan.View).X *direction;
                view.Transform = transform;
                if (velocity >= 100 || velocity >= -50 && Math.Abs(distance) >= 0.5)
                {
                    //TODO: Review this... Uses FLT_EPSILON
                    //// bug workaround: animation briefly resets after call to finishInteractiveTransition() but before animateTransition completion is called.
                    //if (NSProcessInfo.ProcessInfo.OperatingSystemVersion.Major == 8 && this.percentComplete > 1f - 1.192092896e-07F) {
                    //            this.updateInteractiveTransition(0.9999);
                    //}
                    this.FinishInteractiveTransition();
                }
                else
                {
                    this.CancelInteractiveTransition();
                }
                break;
            }
        }
        UIImage ChangeOrientation(UIImage rotatedImage)
        {
            float             width      = rotatedImage.CGImage.Width;
            float             height     = rotatedImage.CGImage.Height;
            CGImage           imgRef     = rotatedImage.CGImage;
            CGAffineTransform transform  = CGAffineTransform.MakeIdentity();
            CGRect            bounds     = new CGRect(0, 0, width, height);
            float             scaleRatio = (float)(bounds.Size.Width / width);
            CGSize            imageSize  = new CGSize(imgRef.Width, imgRef.Height);

            var orient = rotatedImage.Orientation;

            switch (orient)
            {
            case UIImageOrientation.Right:
                bounds.Size = new CGSize(bounds.Size.Height, bounds.Size.Width);
                transform   = CGAffineTransform.MakeTranslation(imageSize.Height, 0.0f);
                transform   = CGAffineTransform.Rotate(transform, (System.nfloat)(Math.PI / 2.0));
                break;

            case UIImageOrientation.Up:     //EXIF = 1
                transform = CGAffineTransform.MakeIdentity();
                break;

            case UIImageOrientation.UpMirrored:     //EXIF = 2
                transform = CGAffineTransform.MakeTranslation(imageSize.Width, 0.0f);
                transform = CGAffineTransform.Scale(transform, -1.0f, 1.0f);
                break;

            case UIImageOrientation.Down:     //EXIF = 3
                transform = CGAffineTransform.MakeTranslation(imageSize.Width, imageSize.Height);
                transform = CGAffineTransform.Rotate(transform, (System.nfloat)Math.PI);
                break;

            case UIImageOrientation.DownMirrored:     //EXIF = 4
                transform = CGAffineTransform.MakeTranslation(0.0f, imageSize.Height);
                transform = CGAffineTransform.Scale(transform, 1.0f, -1.0f);
                break;

            case UIImageOrientation.LeftMirrored:     //EXIF = 5
                bounds.Size = new CGSize(bounds.Size.Height, bounds.Size.Width);
                transform   = CGAffineTransform.MakeTranslation(imageSize.Height, imageSize.Width);
                transform   = CGAffineTransform.Scale(transform, -1.0f, 1.0f);
                transform   = CGAffineTransform.Rotate(transform, (System.nfloat)(3.0 * Math.PI / 2.0));
                break;

            case UIImageOrientation.Left:     //EXIF = 6
                bounds.Size = new CGSize(bounds.Size.Height, bounds.Size.Width);
                transform   = CGAffineTransform.MakeTranslation(0.0f, imageSize.Width);
                transform   = CGAffineTransform.Rotate(transform, (System.nfloat)(3.0 * Math.PI / 2.0));
                break;

            case UIImageOrientation.RightMirrored:     //EXIF = 7
                bounds.Size = new CGSize(bounds.Size.Height, bounds.Size.Width);
                transform   = CGAffineTransform.MakeScale(-1.0f, 1.0f);
                transform   = CGAffineTransform.Rotate(transform, (System.nfloat)(Math.PI / 2.0));
                break;
            }

            UIGraphics.BeginImageContext(bounds.Size);
            CGContext context = UIGraphics.GetCurrentContext();

            if (orient == UIImageOrientation.Right || orient == UIImageOrientation.Left)
            {
                context.ScaleCTM(-scaleRatio, scaleRatio);
                context.TranslateCTM(-height, 0);
            }
            else
            {
                context.ScaleCTM(scaleRatio, -scaleRatio);
                context.TranslateCTM(0, -height);
            }

            context.ConcatCTM(transform);
            context.DrawImage(new CGRect(0, 0, width, height), imgRef);
            UIImage imageCopy = UIGraphics.GetImageFromCurrentImageContext();

            UIGraphics.EndImageContext();
            NSData str = imageCopy.AsPNG();

            return(imageCopy);
        }
 private static extern CGRect[] _RectsFromGlyphs(IntPtr glyphs, CGAffineTransform t, CGRect boundingBox);
        public void HideMenuStart()
        {
            if (menuObserver != null)
            {
                NSNotificationCenter.DefaultCenter.RemoveObserver(menuObserver);
            }

            var mainViewController = this.viewControllerForPresentedMenu;
            var menuView           = this.PresentDirection == UIRectEdge.Left ? SideMenuManager.LeftNavigationController?.View : SideMenuManager.RightNavigationController?.View;

            if (mainViewController == null || menuView == null)
            {
                return;
            }

            menuView.Transform = CGAffineTransform.MakeIdentity();
            mainViewController.View.Transform = CGAffineTransform.MakeIdentity();
            mainViewController.View.Alpha     = 1;
            this.TapView.Frame = new CGRect(0, 0, mainViewController.View.Frame.Width, mainViewController.View.Frame.Height);
            var frame = menuView.Frame;

            frame.Y        = 0;
            frame.Size     = new CGSize(SideMenuManager.MenuWidth, mainViewController.View.Frame.Height);
            menuView.Frame = frame;
            if (this.StatusBarView != null)
            {
                this.StatusBarView.Frame = UIApplication.SharedApplication.StatusBarFrame;
                this.StatusBarView.Alpha = 0;
            }

            CGRect menuFrame;
            CGRect viewFrame;

            switch (SideMenuManager.PresentMode)
            {
            case SideMenuManager.MenuPresentMode.ViewSlideOut:
                menuView.Alpha = 1 - (float)SideMenuManager.AnimationFadeStrength;

                menuFrame      = menuView.Frame;
                menuFrame.X    = (float)(this.PresentDirection == UIRectEdge.Left ? 0 : mainViewController.View.Frame.Width - SideMenuManager.MenuWidth);
                menuView.Frame = menuFrame;

                viewFrame   = mainViewController.View.Frame;
                viewFrame.X = 0;
                mainViewController.View.Frame = viewFrame;

                menuView.Transform = CGAffineTransform.MakeScale((float)SideMenuManager.AnimationTransformScaleFactor, (float)SideMenuManager.AnimationTransformScaleFactor);
                break;

            case SideMenuManager.MenuPresentMode.ViewSlideInOut:
                menuView.Alpha = 1;

                menuFrame      = menuView.Frame;
                menuFrame.X    = this.PresentDirection == UIRectEdge.Left ? -menuView.Frame.Width : mainViewController.View.Frame.Width;
                menuView.Frame = menuFrame;

                viewFrame   = mainViewController.View.Frame;
                viewFrame.X = 0;
                mainViewController.View.Frame = viewFrame;
                break;

            case SideMenuManager.MenuPresentMode.MenuSlideIn:
                menuView.Alpha = 1;

                menuFrame      = menuView.Frame;
                menuFrame.X    = this.PresentDirection == UIRectEdge.Left ? -menuView.Frame.Width : mainViewController.View.Frame.Width;
                menuView.Frame = menuFrame;
                break;

            case SideMenuManager.MenuPresentMode.MenuDissolveIn:
                menuView.Alpha = 0;

                menuFrame      = menuView.Frame;
                menuFrame.X    = (float)(this.PresentDirection == UIRectEdge.Left ? 0 : mainViewController.View.Frame.Width - SideMenuManager.MenuWidth);
                menuView.Frame = menuFrame;

                viewFrame   = mainViewController.View.Frame;
                viewFrame.X = 0;
                mainViewController.View.Frame = viewFrame;
                break;
            }
        }
		CVPixelBuffer newRenderedPixelBufferForRequest (AVAsynchronousVideoCompositionRequest request, out NSError error )
		{
			CVPixelBuffer dstPixels;
			float tweenFactor =(float) FactorForTimeInRange (request.CompositionTime, request.VideoCompositionInstruction.TimeRange);

			var currentInstruction = (CustomVideoCompositionInstruction)request.VideoCompositionInstruction;

			CVPixelBuffer foregroundSourceBuffer = request.SourceFrameByTrackID (currentInstruction.ForegroundTrackID);
			CVPixelBuffer backgroundSourceBuffer = request.SourceFrameByTrackID (currentInstruction.BackgroundTrackID);

			dstPixels = renderContext.CreatePixelBuffer ();

			if (renderContextDidChange) {
				var renderSize = renderContext.Size;
				var destinationSize = new CGSize (dstPixels.Width, dstPixels.Height);
				var renderContextTransform = new CGAffineTransform (renderSize.Width / 2, 0, 0, renderSize.Height / 2, renderSize.Width / 2, renderSize.Height / 2);
				var destinationTransform = new CGAffineTransform (2 / destinationSize.Width, 0, 0, 2 / destinationSize.Height, -1, -1);
				var normalizedRenderTransform = CGAffineTransform.Multiply( CGAffineTransform.Multiply(renderContextTransform, renderContext.RenderTransform), destinationTransform);
				oglRender.RenderTransform = normalizedRenderTransform;

				renderContextDidChange = false;
			}

			oglRender.RenderPixelBuffer (dstPixels, foregroundSourceBuffer, backgroundSourceBuffer, tweenFactor);

			error = null;
			return dstPixels;
		}
        public void PresentMenuStart(CGSize?size = null)
        {
            if (size == null)
            {
                size = SideMenuManager.appScreenRect.Size;
            }

            var menuView           = this.PresentDirection == UIRectEdge.Left ? SideMenuManager.LeftNavigationController?.View : SideMenuManager.RightNavigationController?.View;
            var mainViewController = this.viewControllerForPresentedMenu;

            if (menuView == null || mainViewController == null)
            {
                return;
            }

            menuView.Transform = CGAffineTransform.MakeIdentity();
            mainViewController.View.Transform = CGAffineTransform.MakeIdentity();
            var menuFrame = menuView.Frame;

            menuFrame.Size = new CGSize(SideMenuManager.MenuWidth, size.Value.Height);
            menuFrame.X    = (float)(this.PresentDirection == UIRectEdge.Left ? 0 : size.Value.Width - SideMenuManager.MenuWidth);
            menuView.Frame = menuFrame;

            if (this.StatusBarView != null)
            {
                this.StatusBarView.Frame = UIApplication.SharedApplication.StatusBarFrame;
                this.StatusBarView.Alpha = 1;
            }

            int    direction = 0;
            CGRect frame;

            switch (SideMenuManager.PresentMode)
            {
            case SideMenuManager.MenuPresentMode.ViewSlideOut:
                menuView.Alpha = 1;
                direction      = this.PresentDirection == UIRectEdge.Left ? 1 : -1;
                frame          = mainViewController.View.Frame;
                frame.X        = direction * (menuView.Frame.Width);
                mainViewController.View.Frame               = frame;
                mainViewController.View.Layer.ShadowColor   = SideMenuManager.ShadowColor.CGColor;
                mainViewController.View.Layer.ShadowRadius  = (float)SideMenuManager.ShadowRadius;
                mainViewController.View.Layer.ShadowOpacity = (float)SideMenuManager.ShadowOpacity;
                mainViewController.View.Layer.ShadowOffset  = new CGSize(0, 0);
                break;

            case SideMenuManager.MenuPresentMode.ViewSlideInOut:
                menuView.Alpha               = 1;
                menuView.Layer.ShadowColor   = SideMenuManager.ShadowColor.CGColor;
                menuView.Layer.ShadowRadius  = (float)SideMenuManager.ShadowRadius;
                menuView.Layer.ShadowOpacity = (float)SideMenuManager.ShadowOpacity;
                menuView.Layer.ShadowOffset  = new CGSize(0, 0);
                direction = this.PresentDirection == UIRectEdge.Left ? 1 : -1;
                frame     = mainViewController.View.Frame;
                frame.X   = direction * (menuView.Frame.Width);
                mainViewController.View.Frame     = frame;
                mainViewController.View.Transform = CGAffineTransform.MakeScale((float)SideMenuManager.AnimationTransformScaleFactor, (float)SideMenuManager.AnimationTransformScaleFactor);
                mainViewController.View.Alpha     = (float)(1 - SideMenuManager.AnimationFadeStrength);
                break;

            case SideMenuManager.MenuPresentMode.MenuSlideIn:
            case SideMenuManager.MenuPresentMode.MenuDissolveIn:
                menuView.Alpha                    = 1;
                menuView.Layer.ShadowColor        = SideMenuManager.ShadowColor.CGColor;
                menuView.Layer.ShadowRadius       = (float)SideMenuManager.ShadowRadius;
                menuView.Layer.ShadowOpacity      = (float)SideMenuManager.ShadowOpacity;
                menuView.Layer.ShadowOffset       = new CGSize(0, 0);
                mainViewController.View.Frame     = new CGRect(0, 0, size.Value.Width, size.Value.Height);
                mainViewController.View.Transform = CGAffineTransform.MakeScale((float)SideMenuManager.AnimationTransformScaleFactor, (float)SideMenuManager.AnimationTransformScaleFactor);
                mainViewController.View.Alpha     = (float)(1 - SideMenuManager.AnimationFadeStrength);
                break;
            }
        }
 public void ResetContextAndState()
 {
     AnnotateUndoManager.RemoveAllActions(this);
     annotationDataCache = new List<IAnnotationData> ();
     annotationDataCacheArchive = new List<IAnnotationData> ();
     bzPath.RemoveAllPoints();
     arrowPoints = new CGPoint[7];
     markerPoints = new CGPoint[5];
     pathStart = CGPoint.Empty;
     counter = 0;
     IncrementImage = null;
     touchesDidMove = false;
     displayTransform = new CGAffineTransform ();
     displayRect = CGRect.Empty;
     contextRect = CGRect.Empty;
     bufferRect = CGRect.Empty;
 }
Exemple #40
0
        public Bitmap(int width, int height, PixelFormat format)
        {
            imageTransform = new CGAffineTransform(1, 0, 0, -1, 0, height);

            int           bitsPerComponent, bytesPerRow;
            CGColorSpace  colorSpace;
            CGBitmapFlags bitmapInfo;
            bool          premultiplied = false;
            int           bitsPerPixel  = 0;

            pixelFormat = format;

            // Don't forget to set the Image width and height for size.
            imageSize.Width  = width;
            imageSize.Height = height;

            switch (format)
            {
            case PixelFormat.Format32bppPArgb:
            case PixelFormat.DontCare:
                premultiplied    = true;
                colorSpace       = CGColorSpace.CreateDeviceRGB();
                bitsPerComponent = 8;
                bitsPerPixel     = 32;
                bitmapInfo       = CGBitmapFlags.PremultipliedLast;
                break;

            case PixelFormat.Format32bppArgb:
                colorSpace       = CGColorSpace.CreateDeviceRGB();
                bitsPerComponent = 8;
                bitsPerPixel     = 32;
                bitmapInfo       = CGBitmapFlags.PremultipliedLast;
                break;

            case PixelFormat.Format32bppRgb:
                colorSpace       = CGColorSpace.CreateDeviceRGB();
                bitsPerComponent = 8;
                bitsPerPixel     = 32;
                bitmapInfo       = CGBitmapFlags.NoneSkipLast;
                break;

            case PixelFormat.Format24bppRgb:
                colorSpace       = CGColorSpace.CreateDeviceRGB();
                bitsPerComponent = 8;
                bitsPerPixel     = 24;
                bitmapInfo       = CGBitmapFlags.None;
                break;

            case PixelFormat.Format8bppIndexed:
                // FIXME: Default palette
                colorSpace       = CGColorSpace.CreateIndexed(CGColorSpace.CreateDeviceRGB(), 255, new byte[3 * 256]);
                bitsPerComponent = 8;
                bitsPerPixel     = 8;
                bitmapInfo       = CGBitmapFlags.None;
                palette          = new ColorPalette(0, new Color[256]);
                break;

            case PixelFormat.Format4bppIndexed:
                // FIXME: Default palette
                colorSpace       = CGColorSpace.CreateIndexed(CGColorSpace.CreateDeviceRGB(), 15, new byte[3 * 16]);
                bitsPerComponent = 4;
                bitsPerPixel     = 4;
                bitmapInfo       = CGBitmapFlags.None;
                palette          = new ColorPalette(0, new Color[16]);
                break;

            case PixelFormat.Format1bppIndexed:
                // FIXME: Default palette
                colorSpace       = CGColorSpace.CreateIndexed(CGColorSpace.CreateDeviceRGB(), 1, new byte[3 * 2]);
                bitsPerComponent = 1;
                bitsPerPixel     = 1;
                bitmapInfo       = CGBitmapFlags.None;
                palette          = new ColorPalette(0, new Color[2] {
                    Color.Black, Color.White
                });
                break;

            default:
                throw new Exception("Format not supported: " + format);
            }

            bytesPerRow = (int)(((long)width * bitsPerPixel + 7) / 8);
            int size = bytesPerRow * height;

            bitmapBlock = Marshal.AllocHGlobal(size);
            unsafe {
                byte *b = (byte *)bitmapBlock;
                for (int i = 0; i < size; i++)
                {
                    b [i] = 0;
                }
            }
            dataProvider  = new CGDataProvider(bitmapBlock, size, true);
            NativeCGImage = NewCGImage(width, height, bitsPerComponent, bitsPerPixel, bytesPerRow, colorSpace, bitmapInfo, dataProvider, null, false, CGColorRenderingIntent.Default);

            dpiWidth = dpiHeight = ConversionHelpers.MS_DPI;
            physicalDimension.Width  = width;
            physicalDimension.Height = height;


            // The physical size may be off on certain implementations.  For instance the dpiWidth and dpiHeight
            // are read using integers in core graphics but in windows it is a float.
            // For example:
            // coregraphics dpiWidth = 24 as integer
            // windows dpiWidth = 24.999935 as float
            // this gives a few pixels difference when calculating the physical size.
            // 256 * 96 / 24 = 1024
            // 256 * 96 / 24.999935 = 983.04
            //
            // https://bugzilla.xamarin.com/show_bug.cgi?id=14365
            // PR: https://github.com/mono/maccore/pull/57
            //

            physicalSize         = new SizeF(physicalDimension.Width, physicalDimension.Height);
            physicalSize.Width  *= ConversionHelpers.MS_DPI / dpiWidth;
            physicalSize.Height *= ConversionHelpers.MS_DPI / dpiHeight;

            rawFormat   = ImageFormat.MemoryBmp;
            pixelFormat = format;

            if (premultiplied)
            {
            }                                  // make compiler happy
        }
        void redrawBitmap()
        {
            if (!TrapState.Shared.HasActiveSnapshotImage) return;

            annotationDataCacheHasChangesSinceChecked = true;

            var setup = isRedrawingAfterOrientationChange || displayRect == CGRect.Empty;

            if (setup) {

                var imageSize = TrapState.Shared.ActiveSnapshotImage.Size;

                var scale = (nfloat)Math.Min(Bounds.Size.Width / imageSize.Width, Bounds.Size.Height / imageSize.Height);

                var scaledSize = CGAffineTransform.MakeScale(scale, scale).TransformSize(imageSize);

                contextRect = new CGRect (CGPoint.Empty, imageSize);

                displayRect = new CGRect (new CGPoint (Bounds.GetMidX() - scaledSize.Width / 2, Bounds.GetMidY() - scaledSize.Height / 2), scaledSize);

                bufferRect = new CGRect (CGPoint.Empty, scaledSize);

                var displayScale = (nfloat)Math.Max(imageSize.Width / Bounds.Size.Width, imageSize.Height / Bounds.Size.Height);

                displayTransform = CGAffineTransform.MakeScale(displayScale, displayScale);

                bufferImageView = new UIImageView (displayRect);
                bufferImageView.BackgroundColor = Colors.Clear;
                AddSubview(bufferImageView);
            }

            UIGraphics.BeginImageContextWithOptions(contextRect.Size, true, 1);

            strokeColor.SetStroke();

            if (IncrementImage != null) {

                IncrementImage.Draw(CGPoint.Empty);
            } else {

                TrapState.Shared.ActiveSnapshotImage.Draw(contextRect);
            }

            if (AnnotateUndoManager.IsRedoing) {

                var undo = annotationDataCacheArchive.LastOrDefault();
                if (undo != null) {
                    annotationDataCacheArchive.Remove(undo);
                    annotationDataCache.Add(undo);
                }
            }

            if (AnnotateUndoManager.IsUndoing) {

                TrapState.Shared.ActiveSnapshotImage.Draw(contextRect);

                var redo = annotationDataCache.LastOrDefault();
                if (redo != null) {
                    annotationDataCache.Remove(redo);
                    annotationDataCacheArchive.Add(redo);
                }
            }

            if (!isRedrawingAfterOrientationChange) {

                var context = UIGraphics.GetCurrentContext();

                context.SaveState();

                context.ConcatCTM(displayTransform);

                if (AnnotateUndoManager.IsUndoing) {

                    calloutCount = 0;

                    foreach (var data in annotationDataCache) {

                        switch (data.Tool) {
                        case Annotate.Tool.Callout:

                            var callout = data as CalloutAnnotation;

                            if (callout != null) {
                                drawCallout(context, callout);
                            }

                            break;
                        case Annotate.Tool.Marker:
                        case Annotate.Tool.Arrow:
                        case Annotate.Tool.Circle:
                        case Annotate.Tool.Square:

                            var annotation = data as PathAnnotation;

                            if (annotation != null) {
                                annotation.Color.SetStroke();
                                annotation.Path.Stroke();

                                if (data.Tool == Annotate.Tool.Arrow) {
                                    annotation.Color.SetFill();
                                    annotation.Path.Fill();
                                }
                            }

                            break;
                        case Annotate.Tool.Color:
                            break;
                        }
                    }

                } else {

                    var data = annotationDataCache.LastOrDefault(); // This takes care of redo

                    if (data != null) {

                        switch (data.Tool) {
                        case Annotate.Tool.Callout:

                            var callout = data as CalloutAnnotation;

                            if (callout != null) {
                                drawCallout(context, callout);
                            }

                            break;
                        case Annotate.Tool.Marker:
                        case Annotate.Tool.Arrow:
                        case Annotate.Tool.Circle:
                        case Annotate.Tool.Square:

                            var annotation = data as PathAnnotation;

                            if (annotation != null) {
                                annotation.Color.SetStroke();
                                annotation.Path.Stroke();

                                if (data.Tool == Annotate.Tool.Arrow) {
                                    annotation.Color.SetFill();
                                    annotation.Path.Fill();
                                }
                            }

                            break;
                        case Annotate.Tool.Color:
                            break;
                        }
                    }
                }

                context.RestoreState();

                AnnotateUndoManager.RegisterUndoWithTarget(this, new Selector ("redrawBitmap"), NSString.Empty);
            }

            isRedrawingAfterOrientationChange = false;

            IncrementImage = UIGraphics.GetImageFromCurrentImageContext();

            UIGraphics.EndImageContext();

            bufferImageView.Image = null;

            SetNeedsDisplay();
        }
Exemple #42
0
 internal Bitmap(CGImage image)
 {
     imageTransform = new CGAffineTransform(1, 0, 0, -1, 0, image.Height);
     InitWithCGImage(image);
     GuessPixelFormat();
 }
        private void InitializeImageFrame(int frame)
        {
            imageTransform = CGAffineTransform.MakeIdentity();

            SetImageInformation (frame);
            var cg = CGImageSource.FromDataProvider(dataProvider).CreateImage(frame, null);
            imageTransform = new CGAffineTransform(1, 0, 0, -1, 0, cg.Height);
            //InitWithCGImage (cg);
            NativeCGImage = cg;

            GuessPixelFormat ();
        }
Exemple #44
0
        internal new void RotateFlip(RotateFlipType rotateFlipType)
        {
            CGAffineTransform rotateFlip = CGAffineTransform.MakeIdentity();

            int width, height;

            width  = (int)NativeCGImage.Width;
            height = (int)NativeCGImage.Height;

            switch (rotateFlipType)
            {
            //			case RotateFlipType.RotateNoneFlipNone:
            //			//case RotateFlipType.Rotate180FlipXY:
            //				rotateFlip = GeomUtilities.CreateRotateFlipTransform (b.Width, b.Height, 0, false, false);
            //				break;
            case RotateFlipType.Rotate90FlipNone:
                //case RotateFlipType.Rotate270FlipXY:
                rotateFlip = GeomUtilities.CreateRotateFlipTransform(ref width, ref height, 90, false, false);
                break;

            case RotateFlipType.Rotate180FlipNone:
                //case RotateFlipType.RotateNoneFlipXY:
                rotateFlip = GeomUtilities.CreateRotateFlipTransform(ref width, ref height, 0, true, true);
                break;

            case RotateFlipType.Rotate270FlipNone:
                //case RotateFlipType.Rotate90FlipXY:
                rotateFlip = GeomUtilities.CreateRotateFlipTransform(ref width, ref height, 270, false, false);
                break;

            case RotateFlipType.RotateNoneFlipX:
                //case RotateFlipType.Rotate180FlipY:
                rotateFlip = GeomUtilities.CreateRotateFlipTransform(ref width, ref height, 0, true, false);
                break;

            case RotateFlipType.Rotate90FlipX:
                //case RotateFlipType.Rotate270FlipY:
                rotateFlip = GeomUtilities.CreateRotateFlipTransform(ref width, ref height, 90, true, false);
                break;

            case RotateFlipType.Rotate180FlipX:
                //case RotateFlipType.RotateNoneFlipY:
                rotateFlip = GeomUtilities.CreateRotateFlipTransform(ref width, ref height, 0, false, true);
                break;

            case RotateFlipType.Rotate270FlipX:
                //case RotateFlipType.Rotate90FlipY:
                rotateFlip = GeomUtilities.CreateRotateFlipTransform(ref width, ref height, 270, true, false);
                break;
            }

            var bytesPerRow      = (width * (int)NativeCGImage.BitsPerPixel + 7) / 8;
            var newBitmapBlock   = Marshal.AllocHGlobal(height * bytesPerRow);
            var newBitmapContext = new CGBitmapContext(newBitmapBlock, width, height, NativeCGImage.BitsPerComponent, bytesPerRow, NativeCGImage.ColorSpace, NativeCGImage.AlphaInfo);

            newBitmapContext.ConcatCTM(rotateFlip);
            newBitmapContext.DrawImage(new CGRect(0, 0, NativeCGImage.Width, NativeCGImage.Height), NativeCGImage);
            newBitmapContext.Flush();

            // If the width or height is not the seme we need to switch the dpiHeight and dpiWidth
            // We should be able to get around this with set resolution later.
            if (NativeCGImage.Width != width || NativeCGImage.Height != height)
            {
                var temp = dpiWidth;
                dpiHeight = dpiWidth;
                dpiWidth  = temp;
            }

            physicalDimension.Width  = (float)width;
            physicalDimension.Height = (float)height;

            physicalSize         = new SizeF(physicalDimension.Width, physicalDimension.Height);
            physicalSize.Width  *= ConversionHelpers.MS_DPI / dpiWidth;
            physicalSize.Height *= ConversionHelpers.MS_DPI / dpiHeight;

            // In windows the RawFormat is changed to MemoryBmp to show that the image has changed.
            rawFormat = ImageFormat.MemoryBmp;

            // Set our transform for this image for the new height
            imageTransform = new CGAffineTransform(1, 0, 0, -1, 0, height);

            // bitmapBlock is owned by dataProvider and freed implicitly
            if (dataProvider != null)
            {
                dataProvider.Dispose();
            }

            if (cachedContext != null)
            {
                cachedContext.Dispose();
            }
            NativeCGImage.Dispose();

            this.bitmapBlock   = newBitmapBlock;
            this.dataProvider  = new CGDataProvider(bitmapBlock, height * bytesPerRow);
            this.NativeCGImage = newBitmapContext.ToImage();
            this.cachedContext = newBitmapContext;
            this.imageSource   = null;

            // update the cached size
            imageSize.Width  = this.Width;
            imageSize.Height = this.Height;
        }
        public Bitmap(int width, int height, PixelFormat format)
        {
            imageTransform = new CGAffineTransform(1, 0, 0, -1, 0, height);

            int bitsPerComponent, bytesPerRow;
            CGColorSpace colorSpace;
            CGBitmapFlags bitmapInfo;
            bool premultiplied = false;
            int bitsPerPixel = 0;

            pixelFormat = format;

            // Don't forget to set the Image width and height for size.
            imageSize.Width = width;
            imageSize.Height = height;

            switch (format){
            case PixelFormat.Format32bppPArgb:
            case PixelFormat.DontCare:
                premultiplied = true;
                colorSpace = CGColorSpace.CreateDeviceRGB ();
                bitsPerComponent = 8;
                bitsPerPixel = 32;
                bitmapInfo = CGBitmapFlags.PremultipliedFirst;
                break;
            case PixelFormat.Format32bppArgb:
                colorSpace = CGColorSpace.CreateDeviceRGB ();
                bitsPerComponent = 8;
                bitsPerPixel = 32;
                bitmapInfo = CGBitmapFlags.PremultipliedFirst;
                break;
            case PixelFormat.Format32bppRgb:
                colorSpace = CGColorSpace.CreateDeviceRGB ();
                bitsPerComponent = 8;
                bitsPerPixel = 32;
                bitmapInfo = CGBitmapFlags.NoneSkipLast;
                break;
            case PixelFormat.Format24bppRgb:
                colorSpace = CGColorSpace.CreateDeviceRGB ();
                bitsPerComponent = 8;
                bitsPerPixel = 32;
                bitmapInfo = CGBitmapFlags.NoneSkipLast;
                break;
            default:
                throw new Exception ("Format not supported: " + format);
            }
            bytesPerRow = width * bitsPerPixel/bitsPerComponent;
            int size = bytesPerRow * height;

            bitmapBlock = Marshal.AllocHGlobal (size);
            var bitmap = new CGBitmapContext (bitmapBlock,
                                          width, height,
                                          bitsPerComponent,
                                          bytesPerRow,
                                          colorSpace,
                                          bitmapInfo);
            // This works for now but we need to look into initializing the memory area itself
            // TODO: Look at what we should do if the image does not have alpha channel
            bitmap.ClearRect (new CGRect (0,0,width,height));

            var provider = new CGDataProvider (bitmapBlock, size, true);
            NativeCGImage = new CGImage (width, height, bitsPerComponent, bitsPerPixel, bytesPerRow, colorSpace, bitmapInfo, provider, null, false, CGColorRenderingIntent.Default);

            dpiWidth = dpiHeight = ConversionHelpers.MS_DPI;
            physicalDimension.Width = width;
            physicalDimension.Height = height;

            // The physical size may be off on certain implementations.  For instance the dpiWidth and dpiHeight
            // are read using integers in core graphics but in windows it is a float.
            // For example:
            // coregraphics dpiWidth = 24 as integer
            // windows dpiWidth = 24.999935 as float
            // this gives a few pixels difference when calculating the physical size.
            // 256 * 96 / 24 = 1024
            // 256 * 96 / 24.999935 = 983.04
            //
            // https://bugzilla.xamarin.com/show_bug.cgi?id=14365
            // PR: https://github.com/mono/maccore/pull/57
            //

            physicalSize = new SizeF (physicalDimension.Width, physicalDimension.Height);
            physicalSize.Width *= ConversionHelpers.MS_DPI / dpiWidth;
            physicalSize.Height *= ConversionHelpers.MS_DPI / dpiHeight;

            rawFormat = ImageFormat.MemoryBmp;
            pixelFormat = format;
        }
        CardView AddCardViewToView(UIView containerView)
        {
            CardView cv = new CardView();

            cv.Update(CurrentMatch);
            cv.TranslatesAutoresizingMaskIntoConstraints = false;
            this.cardView = cv;
            containerView.AddSubview(cv);

            UISwipeGestureRecognizer swipeUpRecognizer = new UISwipeGestureRecognizer(HandleSwipeUp);

            swipeUpRecognizer.Direction = UISwipeGestureRecognizerDirection.Up;
            cv.AddGestureRecognizer(swipeUpRecognizer);

            UISwipeGestureRecognizer swipeDownRecognizer = new UISwipeGestureRecognizer(HandleSwipeDown);

            swipeDownRecognizer.Direction = UISwipeGestureRecognizerDirection.Down;
            cv.AddGestureRecognizer(swipeDownRecognizer);

            string sayHelloName = "Say hello".LocalizedString(@"Accessibility action to say hello");

            helloAction = new UIAccessibilityCustomAction(sayHelloName, probe: SayHello);

            string sayGoodbyeName = "Say goodbye".LocalizedString("Accessibility action to say goodbye");

            goodbyeAction = new UIAccessibilityCustomAction(sayGoodbyeName, probe: SayGoodbye);

            UIView[] elements = NSArray.FromArray <UIView> ((NSArray)cv.GetAccessibilityElements());
            foreach (UIView element in elements)
            {
                element.AccessibilityCustomActions = new UIAccessibilityCustomAction[] { helloAction, goodbyeAction }
            }
            ;

            return(cv);
        }

        void HandleSwipeUp(UISwipeGestureRecognizer gestureRecognizer)
        {
            if (gestureRecognizer.State == UIGestureRecognizerState.Recognized)
            {
                SayHello(helloAction);
            }
        }

        void HandleSwipeDown(UISwipeGestureRecognizer gestureRecognizer)
        {
            if (gestureRecognizer.State == UIGestureRecognizerState.Recognized)
            {
                SayGoodbye(goodbyeAction);
            }
        }

        UIView AddAllMatchesViewExplanatoryViewToContainerView(UIView containerView, List <NSLayoutConstraint> constraints)
        {
            UIView overlayView = AddOverlayViewToContainerView(containerView);

            // Start out hidden
            // This view will become visible once all matches have been viewed
            overlayView.Alpha = 0f;

            UILabel label = StyleUtilities.CreateStandardLabel();

            label.Font = StyleUtilities.LargeFont;
            label.Text = "Stay tuned for more matches!".LocalizedString("Shown when all matches have been viewed");
            overlayView.AddSubview(label);

            // Center the overlay view
            constraints.Add(NSLayoutConstraint.Create(overlayView, NSLayoutAttribute.CenterX, NSLayoutRelation.Equal, containerView, NSLayoutAttribute.CenterX, 1f, 0f));
            constraints.Add(NSLayoutConstraint.Create(overlayView, NSLayoutAttribute.CenterY, NSLayoutRelation.Equal, containerView, NSLayoutAttribute.CenterY, 1f, 0f));

            // Position the label in the overlay view
            constraints.Add(NSLayoutConstraint.Create(label, NSLayoutAttribute.Top, NSLayoutRelation.Equal, overlayView, NSLayoutAttribute.Top, 1f, StyleUtilities.ContentVerticalMargin));
            constraints.Add(NSLayoutConstraint.Create(label, NSLayoutAttribute.Bottom, NSLayoutRelation.Equal, overlayView, NSLayoutAttribute.Bottom, 1f, -1 * StyleUtilities.ContentVerticalMargin));
            constraints.Add(NSLayoutConstraint.Create(label, NSLayoutAttribute.Leading, NSLayoutRelation.Equal, overlayView, NSLayoutAttribute.Leading, 1f, StyleUtilities.ContentHorizontalMargin));
            constraints.Add(NSLayoutConstraint.Create(label, NSLayoutAttribute.Trailing, NSLayoutRelation.Equal, overlayView, NSLayoutAttribute.Trailing, 1f, -1 * StyleUtilities.ContentHorizontalMargin));

            return(overlayView);
        }

        bool SayHello(UIAccessibilityCustomAction customAction)
        {
            AnimateCardsForHello(true);
            return(true);
        }

        bool SayGoodbye(UIAccessibilityCustomAction customAction)
        {
            AnimateCardsForHello(false);
            return(true);
        }

        void AnimateCardsForHello(bool forHello)
        {
            AnimateCardOffScreenToTop(forHello, () => {
                currentMatchIndex++;
                Person nextMatch = CurrentMatch;
                if (nextMatch != null)
                {
                    // Show the next match's profile in the card
                    cardView.Update(nextMatch);

                    // Ensure that the view's layout is up to date before we animate it
                    View.LayoutIfNeeded();

                    if (UIAccessibility.IsReduceMotionEnabled)
                    {
                        // Fade the card into view
                        FadeCardIntoView();
                    }
                    else
                    {
                        // Zoom the new card from a tiny point into full view
                        ZoomCardIntoView();
                    }
                }
                else
                {
                    // Hide the card
                    cardView.Hidden = true;

                    // Fade in the "Stay tuned for more matches" blurb
                    UIView.Animate(FadeAnimationDuration, () => {
                        swipeInstructionsView.Alpha           = 0f;
                        allMatchesViewedExplanatoryView.Alpha = 1f;
                    });
                }

                UIAccessibility.PostNotification(UIAccessibilityPostNotification.LayoutChanged, null);
            });
        }

        void FadeCardIntoView()
        {
            cardView.Alpha = 0f;
            UIView.Animate(FadeAnimationDuration, () => {
                cardView.Alpha = 1f;
            });
        }

        void ZoomCardIntoView()
        {
            cardView.Transform = CGAffineTransform.MakeScale(0f, 0f);
            UIView.Animate(ZoomAnimationDuration, () => {
                cardView.Transform = CGAffineTransform.MakeIdentity();
            });
        }

        void AnimateCardOffScreenToTop(bool toTop, Action completion)
        {
            NSLayoutConstraint offScreenConstraint = null;

            if (toTop)
            {
                offScreenConstraint = NSLayoutConstraint.Create(cardView, NSLayoutAttribute.Bottom, NSLayoutRelation.Equal, View, NSLayoutAttribute.Top, 1f, 0f);
            }
            else
            {
                offScreenConstraint = NSLayoutConstraint.Create(cardView, NSLayoutAttribute.Top, NSLayoutRelation.Equal, View, NSLayoutAttribute.Bottom, 1f, 0f);
            }

            View.LayoutIfNeeded();

            UIView.Animate(SwipeAnimationDuration, () => {
                // Slide the card off screen
                View.RemoveConstraints(cardViewVerticalConstraints);
                View.AddConstraint(offScreenConstraint);
                View.LayoutIfNeeded();
            }, () => {
                // Bring the card back into view
                View.RemoveConstraint(offScreenConstraint);
                View.AddConstraints(cardViewVerticalConstraints);

                if (completion != null)
                {
                    completion();
                }
            });
        }

        UIView AddSwipeInstructionsToContainerView(UIView containerView, List <NSLayoutConstraint> constraints)
        {
            UIView overlayView = AddOverlayViewToContainerView(containerView);

            UILabel swipeInstructionsLabel = StyleUtilities.CreateStandardLabel();

            swipeInstructionsLabel.Font = StyleUtilities.LargeFont;
            overlayView.AddSubview(swipeInstructionsLabel);
            swipeInstructionsLabel.Text = "Swipe ↑ to say \"Hello!\"\nSwipe ↓ to say \"Goodbye...\"".LocalizedString("Instructions for the Matches page");
            swipeInstructionsLabel.AccessibilityLabel = "Swipe up to say \"Hello!\"\nSwipe down to say \"Goodbye\"".LocalizedString("Accessibility instructions for the Matches page");

            float overlayMargin = StyleUtilities.OverlayMargin;
            NSLayoutConstraint topMarginConstraint = NSLayoutConstraint.Create(overlayView, NSLayoutAttribute.Top, NSLayoutRelation.Equal, TopLayoutGuide, NSLayoutAttribute.Bottom, 1f, overlayMargin);
            float priority = (int)UILayoutPriority.Required - 1;

            topMarginConstraint.Priority = priority;
            constraints.Add(topMarginConstraint);

            // Position the label inside the overlay view
            constraints.Add(NSLayoutConstraint.Create(swipeInstructionsLabel, NSLayoutAttribute.Top, NSLayoutRelation.Equal, overlayView, NSLayoutAttribute.Top, 1f, HelloGoodbyeVerticalMargin));
            constraints.Add(NSLayoutConstraint.Create(swipeInstructionsLabel, NSLayoutAttribute.CenterX, NSLayoutRelation.Equal, overlayView, NSLayoutAttribute.CenterX, 1f, 0f));
            constraints.Add(NSLayoutConstraint.Create(overlayView, NSLayoutAttribute.Bottom, NSLayoutRelation.Equal, swipeInstructionsLabel, NSLayoutAttribute.Bottom, 1f, HelloGoodbyeVerticalMargin));

            // Center the overlay view horizontally
            constraints.Add(NSLayoutConstraint.Create(overlayView, NSLayoutAttribute.Left, NSLayoutRelation.Equal, containerView, NSLayoutAttribute.Left, 1f, overlayMargin));
            constraints.Add(NSLayoutConstraint.Create(overlayView, NSLayoutAttribute.Right, NSLayoutRelation.Equal, containerView, NSLayoutAttribute.Right, 1f, -overlayMargin));

            return(overlayView);
        }

        UIView AddOverlayViewToContainerView(UIView containerView)
        {
            UIView overlayView = new UIView {
                BackgroundColor = StyleUtilities.OverlayColor,
                TranslatesAutoresizingMaskIntoConstraints = false,
            };

            overlayView.Layer.CornerRadius = StyleUtilities.OverlayCornerRadius;
            containerView.AddSubview(overlayView);

            return(overlayView);
        }
    }
        internal void NativeDrawString(string s, Font font, Color brush, RectangleF layoutRectangle, StringFormat stringFormat)
        {
            if (font == null)
                throw new ArgumentNullException ("font");

            if (s == null || s.Length == 0)
                return;

            var attributedString = buildAttributedString(s, font, brush);

            // Work out the geometry
            RectangleF insetBounds = layoutRectangle;
            bool layoutAvailable = true;

            if (insetBounds.Size == SizeF.Empty)
            {
                insetBounds.Size = new SizeF (8388608, 8388608);
                layoutAvailable = false;
            }

            PointF textPosition = new PointF(insetBounds.X,
                                             insetBounds.Y);

            float boundsWidth = insetBounds.Width;

            // Calculate the lines
            int start = 0;
            int length = (int)attributedString.Length;

            var typesetter = new CTTypesetter(attributedString);

            float baselineOffset = 0;

            // First we need to calculate the offset for Vertical Alignment if we
            // are using anything but Top
            if (layoutAvailable && stringFormat.LineAlignment != StringAlignment.Near) {
                while (start < length) {
                    int count = (int)typesetter.SuggestLineBreak (start, boundsWidth);
                    var line = typesetter.GetLine (new NSRange(start, count));

                    // Create and initialize some values from the bounds.
                    nfloat ascent;
                    nfloat descent;
                    nfloat leading;
                    line.GetTypographicBounds (out ascent, out descent, out leading);
                    baselineOffset += (float)Math.Ceiling (ascent + descent + leading + 1); // +1 matches best to CTFramesetter's behavior
                    line.Dispose ();
                    start += count;
                }
            }

            start = 0;

            while (start < length && textPosition.Y < insetBounds.Bottom)
            {

                // Now we ask the typesetter to break off a line for us.
                // This also will take into account line feeds embedded in the text.
                //  Example: "This is text \n with a line feed embedded inside it"
                int count = (int)typesetter.SuggestLineBreak(start, boundsWidth);
                var line = typesetter.GetLine(new NSRange(start, count));

                // Create and initialize some values from the bounds.
                nfloat ascent;
                nfloat descent;
                nfloat leading;
                double lineWidth = line.GetTypographicBounds(out ascent, out descent, out leading);

                if (!layoutAvailable)
                {
                    insetBounds.Width = (float)lineWidth;
                    insetBounds.Height = (float)(ascent + descent + leading);
                }

                // Calculate the string format if need be
                var penFlushness = 0.0f;

                if (stringFormat.Alignment == StringAlignment.Far)
                    penFlushness = (float)line.GetPenOffsetForFlush(1.0f, insetBounds.Width);
                else if (stringFormat.Alignment == StringAlignment.Center)
                    penFlushness = (float)line.GetPenOffsetForFlush(0.5f, insetBounds.Width);

                // initialize our Text Matrix or we could get trash in here
                var textMatrix = new CGAffineTransform (
                                     1, 0, 0, -1, 0, ascent);

                if (stringFormat.LineAlignment == StringAlignment.Near)
                    textMatrix.Translate (penFlushness + textPosition.X, textPosition.Y); //insetBounds.Height - textPosition.Y -(float)Math.Floor(ascent - 1));
                if (stringFormat.LineAlignment == StringAlignment.Center)
                    textMatrix.Translate (penFlushness + textPosition.X, textPosition.Y + ((insetBounds.Height / 2) - (baselineOffset / 2)) );  // -(float)Math.Floor(ascent)
                if (stringFormat.LineAlignment == StringAlignment.Far)
                    textMatrix.Translate(penFlushness + textPosition.X,  textPosition.Y + ((insetBounds.Height) - (baselineOffset)));

                var glyphRuns = line.GetGlyphRuns ();

                for (int glyphRunIndex = 0; glyphRunIndex < glyphRuns.Length; glyphRunIndex++)
                {

                    var glyphRun = glyphRuns [glyphRunIndex];
                    var glyphs = glyphRun.GetGlyphs ();
                    var glyphPositions = glyphRun.GetPositions ();
                    //var textMatrix = glyphRun.TextMatrix;

                    // Create and initialize some values from the bounds.
                    float glyphAscent;
                    float glyphDescent;
                    float glyphLeading;

                    var elementPoints = new PointF [3];

                    for (int glyphIndex = 0; glyphIndex < glyphs.Length; glyphIndex++)
                    {
                        if (glyphIndex > 0)
                        {
                            textMatrix.x0 += glyphPositions [glyphIndex].X - glyphPositions[glyphIndex - 1].X;
                            textMatrix.y0 += glyphPositions [glyphIndex].Y - glyphPositions[glyphIndex - 1].Y;
                        }

                        var glyphPath = font.nativeFont.GetPathForGlyph (glyphs [glyphIndex]);

                        // glyphPath = null if it is a white space character
                        if (glyphPath != null) {

                            glyphPath.Apply (
                                delegate (CGPathElement pathElement) {

                                    elementPoints[0] = textMatrix.TransformPoint(pathElement.Point1).ToPointF ();
                                    elementPoints[1] = textMatrix.TransformPoint(pathElement.Point2).ToPointF ();
                                        elementPoints[2] = textMatrix.TransformPoint(pathElement.Point3).ToPointF ();
                                //Console.WriteLine ("Applying {0} - {1}, {2}, {3}", pathElement.Type, elementPoints[0], elementPoints[1], elementPoints[2]);

                                        // now add position offsets
                                        switch(pathElement.Type)
                                        {
                                        case CGPathElementType.MoveToPoint:
                                            start_new_fig = true;
                                            Append(elementPoints[0].X, elementPoints[0].Y,PathPointType.Line,true);
                                            break;
                                        case CGPathElementType.AddLineToPoint:
                                            var lastPoint = points[points.Count - 1];
                                            AppendPoint(lastPoint, PathPointType.Line, false);
                                            AppendPoint(elementPoints[0], PathPointType.Line, false);
                                            break;
                                        case CGPathElementType.AddCurveToPoint:
                                        case CGPathElementType.AddQuadCurveToPoint:
                                            //  This is the only thing I can think of right now for the fonts that
                                            //  I have tested.  See the description of the quadraticToCubic method for
                                            //  more information

                                            // Get the last point
                                            var pt1 = points[points.Count - 1];
                                            var pt2 = PointF.Empty;
                                            var pt3 = PointF.Empty;
                                            var pt4 = elementPoints[1];
                                            GeomUtilities.QuadraticToCubic(pt1, elementPoints[0], elementPoints[1], out pt2, out pt3);
                                            Append (pt1.X, pt1.Y, PathPointType.Line, true);
                                            AppendBezier (pt2.X, pt2.Y, pt3.X, pt3.Y, pt4.X, pt4.Y);
                                            break;
                                        case CGPathElementType.CloseSubpath:
                                            CloseFigure();
                                            break;
                                        }

                                }

                            );
                        }

                    }
                }

                // Move the index beyond the line break.
                start += count;
                textPosition.Y += (float)Math.Ceiling(ascent + descent + leading + 1); // +1 matches best to CTFramesetter's behavior
                line.Dispose();

            }
        }
Exemple #48
0
 static UIImage imageWithPDFNamed(string name, float scale)
 {
     return(imageWithPDFNamed(name, scale, CGAffineTransform.MakeIdentity()));
 }
        public void DrawString(string s, Font font, Brush brush, RectangleF layoutRectangle, StringFormat format = null)
        {
            if (font == null)
                throw new ArgumentNullException ("font");
            if (brush == null)
                throw new ArgumentNullException ("brush");
            if (s == null || s.Length == 0)
                return;

            if (format == null)
            {
                format = StringFormat.GenericDefault;
            }

            // TODO: Take into consideration units

            // Not sure we need the Save and Restore around this yet.
            context.SaveState();

            // TextMatrix is not part of the Graphics State and Restore
            var saveMatrix = context.TextMatrix;
            bool layoutAvailable = true;

            //			context.SelectFont ( font.nativeFont.PostScriptName,
            //			                    font.SizeInPoints,
            //			                    CGTextEncoding.MacRoman);
            //
            //			context.SetCharacterSpacing(1);
            //			context.SetTextDrawingMode(CGTextDrawingMode.Fill); // 5
            //
            //			// Setup both the stroke and the fill ?
            //			brush.Setup(this, true);
            //			brush.Setup(this, false);
            //
            //			var textMatrix = font.nativeFont.Matrix;
            //
            //			textMatrix.Scale(1,-1);
            //			context.TextMatrix = textMatrix;
            //
            //			context.ShowTextAtPoint(layoutRectangle.X,
            //			                        layoutRectangle.Y + font.nativeFont.CapHeightMetric, s);
            //
            //
            // First we call the brush with a fill of false so the brush can setup the stroke color
            // that the text will be using.
            // For LinearGradientBrush this will setup a TransparentLayer so the gradient can
            // be filled at the end.  See comments.
            brush.Setup(this, false); // Stroke

            // I think we only Fill the text with no Stroke surrounding
            context.SetTextDrawingMode(CGTextDrawingMode.Fill);

            var attributedString = buildAttributedString(s, font, format, lastBrushColor);

            // Work out the geometry
            RectangleF insetBounds = layoutRectangle;
            if (insetBounds.Size == SizeF.Empty)
            {
                insetBounds.Width = boundingBox.Width;
                insetBounds.Height = boundingBox.Height;
                layoutAvailable = false;

                if (format.LineAlignment != StringAlignment.Near)
                {
                    insetBounds.Size = MeasureString (s, font);
                }

            }

            PointF textPosition = new PointF(insetBounds.X,
                                             insetBounds.Y);

            float boundsWidth = insetBounds.Width;

            // Calculate the lines
            int start = 0;
            int length = (int)attributedString.Length;
            float baselineOffset = 0;

            var typesetter = new CTTypesetter(attributedString);

            // First we need to calculate the offset for Vertical Alignment if we
            // are using anything but Top
            if (layoutAvailable && format.LineAlignment != StringAlignment.Near) {
                while (start < length) {
                    int count = (int)typesetter.SuggestLineBreak (start, boundsWidth);
                    var line = typesetter.GetLine (new NSRange(start, count));

                    // Create and initialize some values from the bounds.
                    nfloat ascent;
                    nfloat descent;
                    nfloat leading;
                    line.GetTypographicBounds (out ascent, out descent, out leading);
                    baselineOffset += (float)Math.Ceiling (ascent + descent + leading + 1); // +1 matches best to CTFramesetter's behavior
                    line.Dispose ();
                    start += count;
                }

                start = 0;
            }

            // If we are drawing vertial direction then we need to rotate our context transform by 90 degrees
            if ((format.FormatFlags & StringFormatFlags.DirectionVertical) == StringFormatFlags.DirectionVertical)
            {
                //textMatrix.Rotate (ConversionHelpers.DegreesToRadians (90));
                var verticalOffset = 0.0f;
                while (start < length) {
                    int count = (int)typesetter.SuggestLineBreak (start, boundsWidth);
                    var line = typesetter.GetLine (new NSRange(start, count));

                    // Create and initialize some values from the bounds.
                    nfloat ascent;
                    nfloat descent;
                    nfloat leading;
                    line.GetTypographicBounds (out ascent, out descent, out leading);
                    verticalOffset += (float)Math.Ceiling (ascent + descent + leading + 1); // +1 matches best to CTFramesetter's behavior
                    line.Dispose ();
                    start += count;
                }
                context.TranslateCTM (layoutRectangle.X, layoutRectangle.Y);
                context.RotateCTM (ConversionHelpers.DegreesToRadians (90));
                context.TranslateCTM (-layoutRectangle.X, -layoutRectangle.Y);
                context.TranslateCTM (0, -verticalOffset);
                start = 0;
            }

            start = 0;
            while (start < length && textPosition.Y < insetBounds.Bottom)
            {

                // Now we ask the typesetter to break off a line for us.
                // This also will take into account line feeds embedded in the text.
                //  Example: "This is text \n with a line feed embedded inside it"
                int count = (int)typesetter.SuggestLineBreak(start, boundsWidth);
                var line = typesetter.GetLine(new NSRange(start, count));

                // Create and initialize some values from the bounds.
                nfloat ascent;
                nfloat descent;
                nfloat leading;
                double lineWidth = line.GetTypographicBounds(out ascent, out descent, out leading);

                // Calculate the string format if need be
                var penFlushness = 0.0f;
                if (format != null)
                {
                    if (layoutAvailable)
                    {
                        if (format.Alignment == StringAlignment.Far)
                            penFlushness = (float)line.GetPenOffsetForFlush(1.0f, boundsWidth);
                        else if (format.Alignment == StringAlignment.Center)
                            penFlushness = (float)line.GetPenOffsetForFlush(0.5f, boundsWidth);
                    }
                    else
                    {
                        // We were only passed in a point so we need to format based
                        // on the point.
                        if (format.Alignment == StringAlignment.Far)
                            penFlushness -= (float)lineWidth;
                        else if (format.Alignment == StringAlignment.Center)
                            penFlushness -= (float)lineWidth / 2.0f;

                    }

                }

                // initialize our Text Matrix or we could get trash in here
                var textMatrix = new CGAffineTransform (
                    1, 0, 0, -1, 0, ascent);

                if (format.LineAlignment == StringAlignment.Near)
                    textMatrix.Translate (penFlushness + textPosition.X, textPosition.Y);
                if (format.LineAlignment == StringAlignment.Center)
                {
                    if (layoutAvailable)
                        textMatrix.Translate (penFlushness + textPosition.X, textPosition.Y + ((insetBounds.Height / 2) - (baselineOffset / 2)));
                    else
                        textMatrix.Translate (penFlushness + textPosition.X, textPosition.Y - ((insetBounds.Height / 2) - (baselineOffset / 2)));
                }

                if (format.LineAlignment == StringAlignment.Far)
                {
                    if (layoutAvailable)
                        textMatrix.Translate (penFlushness + textPosition.X, textPosition.Y + ((insetBounds.Height) - (baselineOffset)));
                    else
                        textMatrix.Translate (penFlushness + textPosition.X, textPosition.Y - ((insetBounds.Height) - (baselineOffset)));
                }

                context.TextMatrix = textMatrix;

                // and draw the line
                line.Draw(context);

                // Move the index beyond the line break.
                start += count;
                textPosition.Y += (float)Math.Ceiling(ascent + descent + leading + 1); // +1 matches best to CTFramesetter's behavior
                line.Dispose();

            }

            // Now we call the brush with a fill of true so the brush can do the fill if need be
            // For LinearGradientBrush this will draw the Gradient and end the TransparentLayer.
            // See comments.
            brush.Setup(this, true); // Fill

            context.TextMatrix = saveMatrix;
            context.RestoreState();
        }
Exemple #50
0
        protected INativeObject GetINativeInstance(Type t)
        {
            var ctor = t.GetConstructor(Type.EmptyTypes);

            if ((ctor != null) && !ctor.IsAbstract)
            {
                return(ctor.Invoke(null) as INativeObject);
            }

            if (!NativeObjectInterfaceType.IsAssignableFrom(t))
            {
                throw new ArgumentException("t");
            }
            switch (t.Name)
            {
            case "CFAllocator":
                return(CFAllocator.SystemDefault);

            case "CFBundle":
                var bundles = CFBundle.GetAll();
                if (bundles.Length > 0)
                {
                    return(bundles [0]);
                }
                else
                {
                    throw new InvalidOperationException(string.Format("Could not create the new instance for type {0}.", t.Name));
                }

            case "CFNotificationCenter":
                return(CFNotificationCenter.Darwin);

            case "CFReadStream":
            case "CFStream":
                CFReadStream  readStream;
                CFWriteStream writeStream;
                CFStream.CreatePairWithSocketToHost("www.google.com", 80, out readStream, out writeStream);
                return(readStream);

            case "CFWriteStream":
                CFStream.CreatePairWithSocketToHost("www.google.com", 80, out readStream, out writeStream);
                return(writeStream);

            case "CFUrl":
                return(CFUrl.FromFile("/etc"));

            case "AudioFile":
                var path = Path.GetFullPath("1.caf");
                var af   = AudioFile.Open(CFUrl.FromFile(path), AudioFilePermission.Read, AudioFileType.CAF);
                return(af);

            case "CFHTTPMessage":
                return(CFHTTPMessage.CreateEmpty(false));

            case "CGBitmapContext":
                byte[] data = new byte [400];
                using (CGColorSpace space = CGColorSpace.CreateDeviceRGB()) {
                    return(new CGBitmapContext(data, 10, 10, 8, 40, space, CGBitmapFlags.PremultipliedLast));
                }

            case "CGContextPDF":
                var filename = Environment.GetFolderPath(Environment.SpecialFolder.CommonDocuments) + "/t.pdf";
                using (var url = new NSUrl(filename))
                    return(new CGContextPDF(url));

            case "CGColorConverter":
                var cvt = new CGColorConverterTriple()
                {
                    Space     = CGColorSpace.CreateGenericRgb(),
                    Intent    = CGColorRenderingIntent.Default,
                    Transform = CGColorConverterTransformType.ApplySpace
                };
                return(new CGColorConverter(null, cvt, cvt, cvt));

            case "CGDataConsumer":
                using (NSMutableData destData = new NSMutableData()) {
                    return(new CGDataConsumer(destData));
                }

            case "CGDataProvider":
                filename = "xamarin1.png";
                return(new CGDataProvider(filename));

            case "CGFont":
                return(CGFont.CreateWithFontName("Courier New"));

            case "CGPattern":
                return(new CGPattern(
                           new RectangleF(0, 0, 16, 16),
                           CGAffineTransform.MakeIdentity(),
                           16, 16,
                           CGPatternTiling.NoDistortion,
                           true,
                           (cgc) => {}));

            case "CMBufferQueue":
                return(CMBufferQueue.CreateUnsorted(2));

            case "CTFont":
                CTFontDescriptorAttributes fda = new CTFontDescriptorAttributes()
                {
                    FamilyName = "Courier",
                    StyleName  = "Bold",
                    Size       = 16.0f
                };
                using (var fd = new CTFontDescriptor(fda))
                    return(new CTFont(fd, 10, CTFontOptions.Default));

            case "CTFontCollection":
                return(new CTFontCollection(new CTFontCollectionOptions()));

            case "CTFontDescriptor":
                fda = new CTFontDescriptorAttributes();
                return(new CTFontDescriptor(fda));

            case "CTTextTab":
                return(new CTTextTab(CTTextAlignment.Left, 2));

            case "CTTypesetter":
                return(new CTTypesetter(new NSAttributedString("Hello, world",
                                                               new CTStringAttributes()
                {
                    ForegroundColorFromContext = true,
                    Font = new CTFont("Arial", 24)
                })));

            case "CTFrame":
                var framesetter = new CTFramesetter(new NSAttributedString("Hello, world",
                                                                           new CTStringAttributes()
                {
                    ForegroundColorFromContext = true,
                    Font = new CTFont("Arial", 24)
                }));
                var bPath = UIBezierPath.FromRect(new RectangleF(0, 0, 3, 3));
                return(framesetter.GetFrame(new NSRange(0, 0), bPath.CGPath, null));

            case "CTFramesetter":
                return(new CTFramesetter(new NSAttributedString("Hello, world",
                                                                new CTStringAttributes()
                {
                    ForegroundColorFromContext = true,
                    Font = new CTFont("Arial", 24)
                })));

            case "CTGlyphInfo":
                return(new CTGlyphInfo("Zapfino", new CTFont("Arial", 24), "Foo"));

            case "CTLine":
                return(new CTLine(new NSAttributedString("Hello, world",
                                                         new CTStringAttributes()
                {
                    ForegroundColorFromContext = true,
                    Font = new CTFont("Arial", 24)
                })));

            case "CGImageDestination":
                var storage = new NSMutableData();
                return(CGImageDestination.Create(new CGDataConsumer(storage), "public.png", 1));

            case "CGImageMetadataTag":
                using (NSString name = new NSString("tagName"))
                    using (var value = new NSString("value"))
                        return(new CGImageMetadataTag(CGImageMetadataTagNamespaces.Exif, CGImageMetadataTagPrefixes.Exif, name, CGImageMetadataType.Default, value));

            case "CGImageSource":
                filename = "xamarin1.png";
                return(CGImageSource.FromUrl(NSUrl.FromFilename(filename)));

            case "SecPolicy":
                return(SecPolicy.CreateSslPolicy(false, null));

            case "SecIdentity":
                using (var options = NSDictionary.FromObjectAndKey(new NSString("farscape"), SecImportExport.Passphrase)) {
                    NSDictionary[] array;
                    var            result = SecImportExport.ImportPkcs12(farscape_pfx, options, out array);
                    if (result != SecStatusCode.Success)
                    {
                        throw new InvalidOperationException(string.Format("Could not create the new instance for type {0} due to {1}.", t.Name, result));
                    }
                    return(new SecIdentity(array [0].LowlevelObjectForKey(SecImportExport.Identity.Handle)));
                }

            case "SecTrust":
                X509Certificate x = new X509Certificate(mail_google_com);
                using (var policy = SecPolicy.CreateSslPolicy(true, "mail.google.com"))
                    return(new SecTrust(x, policy));

            case "SslContext":
                return(new SslContext(SslProtocolSide.Client, SslConnectionType.Stream));

            case "UIFontFeature":
                return(new UIFontFeature(CTFontFeatureNumberSpacing.Selector.ProportionalNumbers));

            case "NetworkReachability":
                return(new NetworkReachability(IPAddress.Loopback, null));

#if !__TVOS__
            case "VTCompressionSession":
            case "VTSession":
                return(VTCompressionSession.Create(1024, 768, CMVideoCodecType.H264, (sourceFrame, status, flags, buffer) => { }, null, (CVPixelBufferAttributes)null));

            case "VTFrameSilo":
                return(VTFrameSilo.Create());

            case "VTMultiPassStorage":
                return(VTMultiPassStorage.Create());
#endif
            case "CFString":
                return(new CFString("test"));

            case "DispatchQueue":
                return(new DispatchQueue("com.example.subsystem.taskXYZ"));

            case "DispatchGroup":
                return(DispatchGroup.Create());

            case "CGColorSpace":
                return(CGColorSpace.CreateAcesCGLinear());

            case "CGGradient":
                CGColor[] cArray = { UIColor.Black.CGColor, UIColor.Clear.CGColor, UIColor.Blue.CGColor };
                return(new CGGradient(null, cArray));

            case "CGImage":
                filename = "xamarin1.png";
                using (var dp = new CGDataProvider(filename))
                    return(CGImage.FromPNG(dp, null, false, CGColorRenderingIntent.Default));

            case "CGColor":
                return(UIColor.Black.CGColor);

            case "CMClock":
                CMClockError ce;
                CMClock      clock = CMClock.CreateAudioClock(out ce);
                if (ce == CMClockError.None)
                {
                    return(clock);
                }
                throw new InvalidOperationException(string.Format("Could not create the new instance for type {0}.", t.Name));

            case "CMTimebase":
                clock = CMClock.CreateAudioClock(out ce);
                if (ce == CMClockError.None)
                {
                    return(new CMTimebase(clock));
                }
                throw new InvalidOperationException(string.Format("Could not create the new instance for type {0}.", t.Name));

            case "CVPixelBufferPool":
                return(new CVPixelBufferPool(
                           new CVPixelBufferPoolSettings(),
                           new CVPixelBufferAttributes(CVPixelFormatType.CV24RGB, 100, 50)
                           ));

            case "SecCertificate":
                using (var cdata = NSData.FromArray(mail_google_com))
                    return(new SecCertificate(cdata));

            case "SecKey":
                SecKey private_key;
                SecKey public_key;
                using (var record = new SecRecord(SecKind.Key)) {
                    record.KeyType       = SecKeyType.RSA;
                    record.KeySizeInBits = 512;                     // it's not a performance test :)
                    SecKey.GenerateKeyPair(record.ToDictionary(), out public_key, out private_key);
                    return(private_key);
                }

            case "SecAccessControl":
                return(new SecAccessControl(SecAccessible.WhenPasscodeSetThisDeviceOnly));

            default:
                throw new InvalidOperationException(string.Format("Could not create the new instance for type {0}.", t.Name));
            }
        }
        /// <summary>
        /// Draws the specified Image at the specified location and with the specified shape and size.
        /// 
        /// The destPoints parameter specifies three points of a parallelogram. The three PointF structures 
        /// represent the upper-left, upper-right, and lower-left corners of the parallelogram. The fourth point 
        /// is extrapolated from the first three to form a parallelogram.
        /// 
        /// The image represented by the image object is scaled and sheared to fit the shape of the parallelogram 
        /// specified by the destPoints parameter.
        /// </summary>
        /// <param name="image">Image.</param>
        /// <param name="destPoints">Destination points.</param>
        public void DrawImage(Image image, PointF [] destPoints)
        {
            if (image == null)
                throw new ArgumentNullException ("image");
            if (destPoints == null)
                throw new ArgumentNullException ("destPoints");
            if (destPoints.Length < 3)
                throw new ArgumentException ("Destination points must be an array with a length of 3 or 4. " +
                                             "A length of 3 defines a parallelogram with the upper-left, upper-right, " +
                                             "and lower-left corners. A length of 4 defines a quadrilateral with the " +
                                             "fourth element of the array specifying the lower-right coordinate.");

            // Windows throws a Not Implemented error if the points are more than 3
            if (destPoints.Length > 3)
                throw new NotImplementedException ();

            // create our rectangle.  Offset is 0 because the CreateGeometricTransform bakes our x,y offset in there.
            var rect = new RectangleF (0,0, destPoints [1].X - destPoints [0].X, destPoints [2].Y - destPoints [0].Y);

            // We need to flip our Y axis so the image appears right side up
            var geoTransform = new CGAffineTransform (1, 0, 0, -1, 0, rect.Height);
            //var geott = GeomUtilities.CreateGeometricTransform (rect, destPoints);
            geoTransform.Multiply (GeomUtilities.CreateGeometricTransform (rect, destPoints));

            // Apply our transform to the context
            context.ConcatCTM (geoTransform);

            // now we draw our image.
            context.DrawImage(rect.ToCGRect (), image.NativeCGImage);

            // Now we revert our image transform from the context
            var revert = CGAffineTransform.CGAffineTransformInvert (geoTransform);
            context.ConcatCTM (revert);
        }
Exemple #52
0
        private void InitWithCGImage(CGImage image, All filter)
        {
            int               width, height, i;
            CGContext         context = null;
            IntPtr            data;
            CGColorSpace      colorSpace;
            IntPtr            tempData;
            bool              hasAlpha;
            CGImageAlphaInfo  info;
            CGAffineTransform transform;
            Size              imageSize;
            SurfaceFormat     pixelFormat;

            //bool sizeToFit = false;

            if (image == null)
            {
                throw new ArgumentException(" NSImage is invalid! ");
            }

            info     = image.AlphaInfo;
            hasAlpha = ((info == CGImageAlphaInfo.PremultipliedLast) || (info == CGImageAlphaInfo.PremultipliedFirst) || (info == CGImageAlphaInfo.Last) || (info == CGImageAlphaInfo.First) ? true : false);

            if (image.ColorSpace != null)
            {
                if (hasAlpha)
                {
                    pixelFormat = SurfaceFormat.Color;
                }
                else
                {
                    pixelFormat = SurfaceFormat.Color;
                }
            }
            else
            {
                pixelFormat = SurfaceFormat.Alpha8;
            }

            imageSize = new Size(image.Width, image.Height);
            transform = CGAffineTransform.MakeIdentity();
            width     = imageSize.Width;

            // Take out the width and height adjustments for power of 2
            //  If not then GetData and SetData is messed up.

            // The Mac opengl version supports non power of 2 textures
            // so we do not have to make them so
//			if ((width != 1) && ((width & (width - 1)) != 0)) {
//				i = 1;
//				while ((sizeToFit ? 2 * i : i) < width)
//					i *= 2;
//				width = i;
//			}

            height = imageSize.Height;

            // The Mac opengl version supports non power of 2 textures
            // so we do not have to make them so
//			if ((height != 1) && ((height & (height - 1)) != 0)) {
//				i = 1;
//				while ((sizeToFit ? 2 * i : i) < height)
//					i *= 2;
//				height = i;
//			}
            // TODO: kMaxTextureSize = 1024
//			while ((width > 1024) || (height > 1024)) {
//				width /= 2;
//				height /= 2;
//				transform = CGAffineTransform.MakeScale (0.5f, 0.5f);
//				imageSize.Width /= 2;
//				imageSize.Height /= 2;
//			}

            float size = Math.Max(width, height);

            if (size > 1024)
            {
                float ratio = 1024 / size;
                width            = (int)(width * ratio);
                height           = (int)(height * ratio);
                transform        = CGAffineTransform.MakeScale(ratio, ratio);
                imageSize.Width  = (int)(imageSize.Width * ratio);
                imageSize.Height = (int)(imageSize.Height * ratio);;
            }

            switch (pixelFormat)
            {
            case SurfaceFormat.Color:
                colorSpace = CGColorSpace.CreateDeviceRGB();
                data       = Marshal.AllocHGlobal(height * width * 4);
                context    = new CGBitmapContext(data, width, height, 8, 4 * width, colorSpace, CGImageAlphaInfo.PremultipliedLast);
                colorSpace.Dispose();
                break;

            case SurfaceFormat.Alpha8:
                data    = Marshal.AllocHGlobal(height * width);
                context = new CGBitmapContext(data, width, height, 8, width, null, CGImageAlphaInfo.Only);
                break;

            default:
                throw new NotSupportedException("Invalid pixel format");
            }

            context.ClearRect(new RectangleF(0, 0, width, height));
            context.TranslateCTM(0, height - imageSize.Height);

            if (!transform.IsIdentity)
            {
                context.ConcatCTM(transform);
            }

            context.DrawImage(new RectangleF(0, 0, image.Width, image.Height), image);

            //Convert "RRRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA" to "RRRRRGGGGGGBBBBB"

            /*
             * if(pixelFormat == SurfaceFormat.Rgb32) {
             *      tempData = Marshal.AllocHGlobal(height * width * 2);
             *
             *      int d32;
             *      short d16;
             *      int inPixel32Count=0,outPixel16Count=0;
             *      for(i = 0; i < width * height; ++i, inPixel32Count+=sizeof(int))
             *      {
             *              d32 = Marshal.ReadInt32(data,inPixel32Count);
             *              short R = (short)((((d32 >> 0) & 0xFF) >> 3) << 11);
             *              short G = (short)((((d32 >> 8) & 0xFF) >> 2) << 5);
             *              short B = (short)((((d32 >> 16) & 0xFF) >> 3) << 0);
             *              d16 = (short)  (R | G | B);
             *              Marshal.WriteInt16(tempData,outPixel16Count,d16);
             *              outPixel16Count += sizeof(short);
             *      }
             *      Marshal.FreeHGlobal(data);
             *      data = tempData;
             * }
             */

            InitWithData(data, pixelFormat, width, height, imageSize, filter);

            context.Dispose();
            Marshal.FreeHGlobal(data);
        }
        private void DrawImage(RectangleF rect, CGImage image, CGAffineTransform transform)
        {
            var trans = transform;
            // Do our translation on the image transform
            trans.Translate (rect.X, rect.Height - image.Height + rect.Y);

            // The translation is already taken care of in the transform
            rect.Y = 0;
            rect.X = 0;

            // Apply our transform to the context
            context.ConcatCTM (trans);

            // we are getting an error somewhere and not sure where
            // I think the image bitmapBlock is being corrupted somewhere
            try {
                context.DrawImage (rect.ToCGRect (), image);
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc.Message);
            }

            // Now we revert our image transform from the context
            var revert = CGAffineTransform.CGAffineTransformInvert (trans);
            context.ConcatCTM (revert);
        }
Exemple #54
0
        public CGContextCanvas(CGContext context)
        {
            this.context = context;
//			context.InterpolationQuality = CGInterpolationQuality.High;
            context.TextMatrix = CGAffineTransform.MakeScale(1, -1);
        }
		public CIImage AffineTransform ()
		{
			// Create an AffineTransform to Skew the Image
			var transform = new CGAffineTransform (1F, .5F, .5F, 1F, 0F, 0F);
			
			var affineTransform = new CIAffineTransform ()
			{
				Image = flower,
				Transform = transform
			};
			
			return affineTransform.OutputImage;
		}
Exemple #56
0
        public static PathData ToCGPath(this Geometry geometry, Transform renderTransform = null)
        {
            PathData pathData = new PathData
            {
                Data = new CGPath()
            };

            CGAffineTransform transform;

            if (renderTransform == null)
            {
                transform = CGAffineTransform.MakeIdentity();
            }
            else
            {
                transform = renderTransform.ToCGAffineTransform();
            }

            if (geometry is LineGeometry)
            {
                LineGeometry lineGeometry = geometry as LineGeometry;
                pathData.Data.MoveToPoint(transform, lineGeometry.StartPoint.ToPointF());
                pathData.Data.AddLineToPoint(transform, lineGeometry.EndPoint.ToPointF());
            }
            else if (geometry is RectangleGeometry)
            {
                Rect rect = (geometry as RectangleGeometry).Rect;
                pathData.Data.AddRect(transform, new CGRect(rect.X, rect.Y, rect.Width, rect.Height));
            }
            else if (geometry is EllipseGeometry)
            {
                EllipseGeometry ellipseGeometry = geometry as EllipseGeometry;

                CGRect rect = new CGRect(
                    ellipseGeometry.Center.X - ellipseGeometry.RadiusX,
                    ellipseGeometry.Center.Y - ellipseGeometry.RadiusY,
                    ellipseGeometry.RadiusX * 2,
                    ellipseGeometry.RadiusY * 2);

                pathData.Data.AddEllipseInRect(transform, rect);
            }
            else if (geometry is GeometryGroup)
            {
                GeometryGroup geometryGroup = geometry as GeometryGroup;

                pathData.IsNonzeroFillRule = geometryGroup.FillRule == FillRule.Nonzero;

                foreach (Geometry child in geometryGroup.Children)
                {
                    PathData pathChild = child.ToCGPath(renderTransform);
                    pathData.Data.AddPath(pathChild.Data);
                }
            }
            else if (geometry is PathGeometry)
            {
                PathGeometry pathGeometry = geometry as PathGeometry;

                pathData.IsNonzeroFillRule = pathGeometry.FillRule == FillRule.Nonzero;

                foreach (PathFigure pathFigure in pathGeometry.Figures)
                {
                    pathData.Data.MoveToPoint(transform, pathFigure.StartPoint.ToPointF());
                    Point lastPoint = pathFigure.StartPoint;

                    foreach (PathSegment pathSegment in pathFigure.Segments)
                    {
                        // LineSegment
                        if (pathSegment is LineSegment)
                        {
                            LineSegment lineSegment = pathSegment as LineSegment;

                            pathData.Data.AddLineToPoint(transform, lineSegment.Point.ToPointF());
                            lastPoint = lineSegment.Point;
                        }
                        // PolyLineSegment
                        else if (pathSegment is PolyLineSegment)
                        {
                            PolyLineSegment polylineSegment = pathSegment as PolyLineSegment;
                            PointCollection points          = polylineSegment.Points;

                            for (int i = 0; i < points.Count; i++)
                            {
                                pathData.Data.AddLineToPoint(transform, points[i].ToPointF());
                            }

                            lastPoint = points[points.Count - 1];
                        }

                        // BezierSegment
                        if (pathSegment is BezierSegment)
                        {
                            BezierSegment bezierSegment = pathSegment as BezierSegment;

                            pathData.Data.AddCurveToPoint(
                                transform,
                                bezierSegment.Point1.ToPointF(),
                                bezierSegment.Point2.ToPointF(),
                                bezierSegment.Point3.ToPointF());

                            lastPoint = bezierSegment.Point3;
                        }
                        // PolyBezierSegment
                        else if (pathSegment is PolyBezierSegment)
                        {
                            PolyBezierSegment polyBezierSegment = pathSegment as PolyBezierSegment;
                            PointCollection   points            = polyBezierSegment.Points;

                            if (points.Count >= 3)
                            {
                                for (int i = 0; i < points.Count; i += 3)
                                {
                                    pathData.Data.AddCurveToPoint(
                                        transform,
                                        points[i].ToPointF(),
                                        points[i + 1].ToPointF(),
                                        points[i + 2].ToPointF());
                                }
                            }

                            lastPoint = points[points.Count - 1];
                        }

                        // QuadraticBezierSegment
                        if (pathSegment is QuadraticBezierSegment)
                        {
                            QuadraticBezierSegment bezierSegment = pathSegment as QuadraticBezierSegment;

                            pathData.Data.AddQuadCurveToPoint(
                                transform,
                                new nfloat(bezierSegment.Point1.X),
                                new nfloat(bezierSegment.Point1.Y),
                                new nfloat(bezierSegment.Point2.X),
                                new nfloat(bezierSegment.Point2.Y));

                            lastPoint = bezierSegment.Point2;
                        }
                        // PolyQuadraticBezierSegment
                        else if (pathSegment is PolyQuadraticBezierSegment)
                        {
                            PolyQuadraticBezierSegment polyBezierSegment = pathSegment as PolyQuadraticBezierSegment;
                            PointCollection            points            = polyBezierSegment.Points;

                            if (points.Count >= 2)
                            {
                                for (int i = 0; i < points.Count; i += 2)
                                {
                                    pathData.Data.AddQuadCurveToPoint(
                                        transform,
                                        new nfloat(points[i + 0].X),
                                        new nfloat(points[i + 0].Y),
                                        new nfloat(points[i + 1].X),
                                        new nfloat(points[i + 1].Y));
                                }
                            }

                            lastPoint = points[points.Count - 1];
                        }
                        // ArcSegment
                        else if (pathSegment is ArcSegment)
                        {
                            ArcSegment arcSegment = pathSegment as ArcSegment;

                            List <Point> points = new List <Point>();

                            GeometryHelper.FlattenArc(
                                points,
                                lastPoint,
                                arcSegment.Point,
                                arcSegment.Size.Width,
                                arcSegment.Size.Height,
                                arcSegment.RotationAngle,
                                arcSegment.IsLargeArc,
                                arcSegment.SweepDirection == SweepDirection.CounterClockwise,
                                1);

                            CGPoint[] cgpoints = new CGPoint[points.Count];

                            for (int i = 0; i < points.Count; i++)
                            {
                                cgpoints[i] = transform.TransformPoint(points[i].ToPointF());
                            }

                            pathData.Data.AddLines(cgpoints);

                            lastPoint = points.Count > 0 ? points[points.Count - 1] : Point.Zero;
                        }
                    }

                    if (pathFigure.IsClosed)
                    {
                        pathData.Data.CloseSubpath();
                    }
                }
            }

            return(pathData);
        }
        public static RectangleF[] RectsFromGlyphs(PSPDFGlyph [] glyphs, CGAffineTransform t, RectangleF boundingBox)
        {
            var objs = new List<NSObject>();

            foreach (var glyph in glyphs)
                objs.Add(glyph);

            NSArray arry = NSArray.FromNSObjects(objs.ToArray());
            return _RectsFromGlyphs(arry.Handle, t, boundingBox);
        }
        public static CGPath ToCGPath(
            this PathF target)
        {
            var path = new CGPath();

            int pointIndex        = 0;
            int arcAngleIndex     = 0;
            int arcClockwiseIndex = 0;

            foreach (var operation in target.PathOperations)
            {
                if (operation == PathOperation.MoveTo)
                {
                    var point = target[pointIndex++];
                    path.MoveToPoint(point.X, point.Y);
                }
                else if (operation == PathOperation.Line)
                {
                    var endPoint = target[pointIndex++];
                    path.AddLineToPoint(endPoint.X, endPoint.Y);
                }

                else if (operation == PathOperation.Quad)
                {
                    var controlPoint = target[pointIndex++];
                    var endPoint     = target[pointIndex++];
                    path.AddQuadCurveToPoint(
                        controlPoint.X,
                        controlPoint.Y,
                        endPoint.X,
                        endPoint.Y);
                }
                else if (operation == PathOperation.Cubic)
                {
                    var controlPoint1 = target[pointIndex++];
                    var controlPoint2 = target[pointIndex++];
                    var endPoint      = target[pointIndex++];
                    path.AddCurveToPoint(
                        controlPoint1.X,
                        controlPoint1.Y,
                        controlPoint2.X,
                        controlPoint2.Y,
                        endPoint.X,
                        endPoint.Y);
                }
                else if (operation == PathOperation.Arc)
                {
                    var   topLeft     = target[pointIndex++];
                    var   bottomRight = target[pointIndex++];
                    float startAngle  = target.GetArcAngle(arcAngleIndex++);
                    float endAngle    = target.GetArcAngle(arcAngleIndex++);
                    var   clockwise   = target.IsArcClockwise(arcClockwiseIndex++);

                    var startAngleInRadians = GraphicsOperations.DegreesToRadians(-startAngle);
                    var endAngleInRadians   = GraphicsOperations.DegreesToRadians(-endAngle);

                    while (startAngleInRadians < 0)
                    {
                        startAngleInRadians += (float)Math.PI * 2;
                    }

                    while (endAngleInRadians < 0)
                    {
                        endAngleInRadians += (float)Math.PI * 2;
                    }

                    var cx     = (bottomRight.X + topLeft.X) / 2;
                    var cy     = (bottomRight.Y + topLeft.Y) / 2;
                    var width  = bottomRight.X - topLeft.X;
                    var height = bottomRight.Y - topLeft.Y;
                    var r      = width / 2;

                    var transform = CGAffineTransform.MakeTranslation(cx, cy);
                    transform = CGAffineTransform.Multiply(CGAffineTransform.MakeScale(1, height / width), transform);

                    path.AddArc(transform, 0, 0, r, startAngleInRadians, endAngleInRadians, !clockwise);
                }
                else if (operation == PathOperation.Close)
                {
                    path.CloseSubpath();
                }
            }

            return(path);
        }
 private static extern RectangleF[] _RectsFromGlyphs(IntPtr glyphs, CGAffineTransform t, RectangleF boundingBox);
		public static Stream RotateImage(UIImage image, int compressionQuality, string pathExtension)
		{
			UIImage imageToReturn = null;
			if (image.Orientation == UIImageOrientation.Up)
			{
				imageToReturn = image;
			}
			else
			{
				var transform = CGAffineTransform.MakeIdentity();

				switch (image.Orientation)
				{
					case UIImageOrientation.Down:
					case UIImageOrientation.DownMirrored:
						transform.Rotate((float)Math.PI);
						transform.Translate(image.Size.Width, image.Size.Height);
						break;

					case UIImageOrientation.Left:
					case UIImageOrientation.LeftMirrored:
						transform.Rotate((float)Math.PI / 2);
						transform.Translate(image.Size.Width, 0);
						break;

					case UIImageOrientation.Right:
					case UIImageOrientation.RightMirrored:
						transform.Rotate(-(float)Math.PI / 2);
						transform.Translate(0, image.Size.Height);
						break;
					case UIImageOrientation.Up:
					case UIImageOrientation.UpMirrored:
						break;
				}

				switch (image.Orientation)
				{
					case UIImageOrientation.UpMirrored:
					case UIImageOrientation.DownMirrored:
						transform.Translate(image.Size.Width, 0);
						transform.Scale(-1, 1);
						break;

					case UIImageOrientation.LeftMirrored:
					case UIImageOrientation.RightMirrored:
						transform.Translate(image.Size.Height, 0);
						transform.Scale(-1, 1);
						break;
					case UIImageOrientation.Up:
					case UIImageOrientation.Down:
					case UIImageOrientation.Left:
					case UIImageOrientation.Right:
						break;
				}

				using var context = new CGBitmapContext(IntPtr.Zero,
														(int)image.Size.Width,
														(int)image.Size.Height,
														image.CGImage.BitsPerComponent,
														image.CGImage.BytesPerRow,
														image.CGImage.ColorSpace,
														image.CGImage.BitmapInfo);
				context.ConcatCTM(transform);
				switch (image.Orientation)
				{
					case UIImageOrientation.Left:
					case UIImageOrientation.LeftMirrored:
					case UIImageOrientation.Right:
					case UIImageOrientation.RightMirrored:
						context.DrawImage(new CGRect(0, 0, image.Size.Height, image.Size.Width), image.CGImage);
						break;
					default:
						context.DrawImage(new CGRect(0, 0, image.Size.Width, image.Size.Height), image.CGImage);
						break;
				}

				using var imageRef = context.ToImage();
				imageToReturn = new UIImage(imageRef, 1, UIImageOrientation.Up);
			}

			pathExtension = pathExtension.ToLowerInvariant();
			var finalQuality = pathExtension == "jpg" ? (compressionQuality / 100f) : 0f;
			var imageData = pathExtension == "png" ? imageToReturn.AsPNG() : imageToReturn.AsJPEG(finalQuality);
			//continue to move down quality , rare instances
			while (imageData == null && finalQuality > 0)
			{
				finalQuality -= 0.05f;
				imageData = imageToReturn.AsJPEG(finalQuality);
			}

			if (imageData == null)
				throw new NullReferenceException("Unable to convert image to jpeg, please ensure file exists or lower quality level");

			var stream = new MemoryStream();
			imageData.AsStream().CopyTo(stream);
			stream.Position = 0;
			imageData.Dispose();
			image.Dispose();
			image = null;
			return stream;

		}