public static UIImage BufferToImage (Color[] buffer, int width, int height) { byte[] bytes = new byte[buffer.Length * 4]; int j = 0; for (int i=0; i<buffer.Length; i++, j+= 4) { bytes[j+0] = buffer[i].R; bytes[j+1] = buffer[i].G; bytes[j+2] = buffer[i].B; bytes[j+3] = 255; } CGDataProvider dataProvider = new CGDataProvider(bytes, 0, bytes.Length); CGImage image = new CGImage( width, height, 8, 32, 4 * width, CGColorSpace.CreateDeviceRGB(), CGBitmapFlags.ByteOrderDefault | CGBitmapFlags.Last, dataProvider, null, false, CGColorRenderingIntent.Default ); return new UIImage(image); }
/// <summary> /// バイト配列からWriteableBitmapを生成する /// </summary> /// <param name="width">幅</param> /// <param name="height">高さ</param> /// <param name="array">ピクセルデータ</param> /// <returns>WriteableBitmapオブジェクト</returns> public static UIImage FromArray(this UIImage bmp, byte[] array) { var cgImage = bmp.CGImage; int width = cgImage.Width; int height = cgImage.Height; int bitsPerComponent = cgImage.BitsPerComponent; int bitsPerPixel = cgImage.BitsPerPixel; int bytesPerRow = cgImage.BytesPerRow; var colorSpace = cgImage.ColorSpace; var bitmapInfo = cgImage.BitmapInfo; var shouldInterpolate = cgImage.ShouldInterpolate; var intent = cgImage.RenderingIntent; // 画像処理後のbyte配列を元にデータプロバイダーを作成する CGImage effectedCgImage; using (var effectedDataProvider = new CGDataProvider(array, 0, array.Length)) { // データプロバイダーからCGImageを作成し、CGImageからUIImageを作成する effectedCgImage = new CGImage( width, height, bitsPerComponent, bitsPerPixel, bytesPerRow, colorSpace, bitmapInfo, effectedDataProvider, null, shouldInterpolate, intent); } return new UIImage(effectedCgImage); }
public System.IO.Stream RenderToStream (byte[] documentData, int pageIndex) { using (MemoryStream ms = new MemoryStream (documentData)) { // open document using (Document doc = new Document (ms)) { // prepare for rendering int width = (int)doc.Pages [pageIndex].Width; int height = (int)doc.Pages [pageIndex].Height; // render the page to a raw bitmap data represented by byte array byte[] imageData = ConvertBGRAtoRGBA(doc.Pages [pageIndex].RenderAsBytes (width,height, new RenderingSettings (), null)); // create CGDataProvider which will serve CGImage creation CGDataProvider dataProvider = new CGDataProvider (imageData, 0, imageData.Length); // create core graphics image using data provider created above, note that // we use CGImageAlphaInfo.Last(ARGB) pixel format CGImage cgImage = new CGImage(width,height,8,32,width*4,CGColorSpace.CreateDeviceRGB(),CGImageAlphaInfo.Last,dataProvider,null,false, CGColorRenderingIntent.Default); // create UIImage and save it to gallery UIImage finalImage = new UIImage (cgImage); return finalImage.AsPNG ().AsStream(); } } }
public void LoadImageSource(string sImg) { CGDataProvider dataProvider = new CGDataProvider(sImg); var rbitmap = CGImage.FromPNG(dataProvider, null, false, CGColorRenderingIntent.Default); if (rbitmap != null) { iOSbitmap = UIImage.FromImage(rbitmap); } }
private static CGFont _CreateLatinMathCg() { var manifestProvider = IosResourceProviders.Manifest(); byte[] buffer = manifestProvider.ManifestContents(LatinMathFontName + ".otf"); using (CGDataProvider fontDataProvider = new CGDataProvider(buffer)) { var r = CGFont.CreateFromProvider(fontDataProvider); return(r); } }
static CGImage DeserializeToCGImage(byte[] ser) { CGDataProvider dataProvider = new CGDataProvider(ser, 0, ser.Length); CGImage img = CGImage.FromPNG(dataProvider, null, false, CGColorRenderingIntent.Default); if (img == null) { throw new FormatException(); } return(img); }
static AppleMathFont() { using var fontDataProvider = new CGDataProvider( Foundation.NSData.FromStream( new Resources.ManifestResourceProvider( System.Reflection.Assembly.GetExecutingAssembly() ).ManifestStream(LatinMathFontName + ".otf") ) ); LatinMathCG = CGFont.CreateFromProvider(fontDataProvider); }
public void FromPNG () { string file = Path.Combine (NSBundle.MainBundle.ResourcePath, "basn3p08.png"); using (var dp = new CGDataProvider (file)) using (var img = CGImage.FromPNG (dp, null, false, CGColorRenderingIntent.Default)) using (var ui = new UIImage (img, 1.0f, UIImageOrientation.Up)) { Assert.IsNotNull (ui.CGImage, "CGImage"); if (TestRuntime.CheckXcodeVersion (7, 0)) Assert.That (img.UTType.ToString (), Is.EqualTo ("public.png"), "UTType"); } }
public IImage LoadImage (Stream stream) { var mem = new MemoryStream ((int)stream.Length); stream.CopyTo (mem); unsafe { fixed (byte *x = mem.GetBuffer ()) { var provider = new CGDataProvider (new IntPtr (x), (int)mem.Length, false); var image = CGImage.FromPNG (provider, null, false, CGColorRenderingIntent.Default); return new CGImageImage (image, 1); } } }
partial void ScreenButton_down(UIButton sender) { if (!isScreen) { ScreenshotView.Hidden = false; ScreenBtn.SetTitle("Hide screen", UIControlState.Normal); isScreen = true; int val = 1920 * 1080 * 4 + 8; //ARGB 1920x1080 + 8(iosspecific) IntPtr b = Marshal.AllocHGlobal(val); int val1 = -1; //return realsize after getvideoshot int val2 = -1; //return realsize after getvideoshot int val3 = 0; //return realsize after getvideoshot int rc = _mediaPlayer.GetVideoShot(b, ref val, ref val1, ref val2, ref val3); if (rc == -2) { System.Console.WriteLine(String.Format("<binary> rc: {0} , not enough space allocated", rc)); Marshal.FreeHGlobal(b); return; } else if (rc == -1) { System.Console.WriteLine(String.Format("<binary> rc: {0} , error", rc)); Marshal.FreeHGlobal(b); return; } CGDataProvider provider = new CGDataProvider(b, val); int bitsPerComponent = 8; int bitsPerPixel = 32; int bytesPerRow = val3; CGColorSpace colorspaceref = CGColorSpace.CreateDeviceRGB(); CGBitmapFlags bitmapinfo = CGBitmapFlags.ByteOrder32Little | CGBitmapFlags.NoneSkipFirst; CGColorRenderingIntent renderintent = CGColorRenderingIntent.Default; CGImage imageref = new CGImage(val1, val2, bitsPerComponent, bitsPerPixel, val3, colorspaceref, bitmapinfo, provider, null, true, renderintent); UIImage img = new UIImage(imageref); ScrenShotImageView.Image = img; Marshal.FreeHGlobal(b); } else { ScreenBtn.SetTitle("Screen", UIControlState.Normal); ScreenshotView.Hidden = true; isScreen = false; } }
public static NSImage ToNSImage(this Image img) { MemoryStream s = new MemoryStream(); img.Save(s, System.Drawing.Imaging.ImageFormat.Png); byte[] b = s.ToArray(); CGDataProvider dp = new CGDataProvider(b, 0, (int)s.Length); s.Flush(); s.Close(); CGImage img2 = CGImage.FromPNG(dp, null, false, CGColorRenderingIntent.Default); return(new NSImage(img2, new SizeF(img2.Width, img2.Height))); }
public UIImage ToImage() { using (var dataProvider = new CGDataProvider(pixelData, 0, pixelData.Length)) { using (var colorSpace = CGColorSpace.CreateDeviceRGB()) { using (var cgImage = new CGImage(width, height, bitsPerComponent, bitsPerComponent * bytesPerPixel, bytesPerPixel * width, colorSpace, CGBitmapFlags.ByteOrderDefault, dataProvider, null, false, CGColorRenderingIntent.Default)) { image.Dispose(); image = null; pixelData = null; return(UIImage.FromImage(cgImage, 0, orientation)); } } } }
public static void LoadFont(string name, string format) { var bundle = NSBundle.FromClass(new Class(typeof(NBMaterialCircularActivityIndicator))); var fontURL = bundle.GetUrlForResource(name, format); var data = NSData.FromUrl(fontURL); var provider = new CGDataProvider(data); var font = CGFont.CreateFromProvider(provider); NSError error; if (!CTFontManager.RegisterGraphicsFont(font, out error)) { throw new NSErrorException(error); } }
public CGImage CreateImageWithAutoReleasePool(int c = 1) { using (var pool = new NSAutoreleasePool()) { var colorSpace = CGColorSpace.CreateDeviceRGB(); var width = 1000; var height = 1000; var bitsPerSample = 8; var components = 3;//RGB var bitsPerPixel = bitsPerSample * components; var bytesPerRow = bitsPerPixel / 8 * width; var bufferToDisplay = new byte[width * height * components]; var bufferDontUse = new byte[width * height * components * 2]; System.Diagnostics.Debug.WriteLine($" Allocated buffer size {bufferToDisplay.Length} + {bufferDontUse.Length}"); System.Diagnostics.Debug.WriteLine($" before local GC {GC.GetTotalMemory(false) - baseMemory}"); bufferDontUse = null; GC.Collect(); System.Diagnostics.Debug.WriteLine($" after local GC {GC.GetTotalMemory(false) - baseMemory}"); int a = 0; for (int cnt = 0; cnt < width * height; cnt++) { bufferToDisplay[a++] = c % 3 == 0 ? (byte)0xFF : (byte)0x00; bufferToDisplay[a++] = c % 3 == 1 ? (byte)0xFF : (byte)0x00; bufferToDisplay[a++] = c % 3 == 2 ? (byte)0xFF : (byte)0x00; } using (var data = new CGDataProvider(bufferToDisplay)) { var cgImage = new CGImage( width, height, bitsPerSample, bitsPerPixel, bytesPerRow, colorSpace, CGBitmapFlags.ByteOrderDefault, data, decode: null, shouldInterpolate: false, intent: CGColorRenderingIntent.Default); bufferToDisplay = null; return(cgImage); } } }
public void Pasteboard_ImagesTest () { string file = Path.Combine (NSBundle.MainBundle.ResourcePath, "basn3p08.png"); using (var dp = new CGDataProvider (file)) { using (var cgimg = CGImage.FromPNG (dp, null, false, CGColorRenderingIntent.Default)) { using (var img = new UIImage (cgimg)) { UIPasteboard.General.Images = new UIImage[] { img }; Assert.AreEqual (1, UIPasteboard.General.Images.Length, "a - length"); UIPasteboard.General.Images = new UIImage[] { img, img }; Assert.AreEqual (2, UIPasteboard.General.Images.Length, "b - length"); Assert.IsNotNull (UIPasteboard.General.Images [0], "b - nonnull[0]"); Assert.IsNotNull (UIPasteboard.General.Images [1], "b - nonnull[0]"); } } } }
public void CreateWithUnownedMemory() { const string canary = "canary"; var source = Encoding.UTF8.GetBytes(canary); IntPtr memory = Marshal.AllocHGlobal(20); Marshal.Copy(source, 0, memory, source.Length); using (var provider = new CGDataProvider(memory, 20, false)) { // `memory` is copied, but not freed (but the copy is freed) Assert.That(provider.Handle, Is.Not.EqualTo(IntPtr.Zero), "Handle"); } // so `memory` still accessible afterward and must be freed // using `canary.Length` since the allocated memory might not be zero'ed // so reading back the string would not hit a null after what we copied Assert.That(Marshal.PtrToStringAuto(memory, canary.Length), Is.EqualTo(canary), "canary check"); Marshal.FreeHGlobal(memory); }
public NativeBitmap(int width, int height, int bitCount) { int bytesInPixel = bitCount / 8; colorSpace = CGColorSpace.CreateDeviceRGB(); int bitsLength = bytesInPixel * width * height; //bits = Marshal.AllocHGlobal (bitsLength); bits = new byte[bitsLength]; Console.WriteLine($"allocating {bits.Length / 1024} KB"); //cgdata = new CGDataProvider (bits, bitsLength); cgdata = new CGDataProvider(bits, 0, bitsLength); cgimage = new CGImage(width, height, 8, bitCount, bytesInPixel * width, colorSpace, CGImageAlphaInfo.None | (CGImageAlphaInfo)CGBitmapFlags.ByteOrder32Big, cgdata, null, false, CGColorRenderingIntent.Default); image = UIImage.FromImage(cgimage); }
public void Save(string path) { var extension = Path.GetExtension(path).ToLowerInvariant(); string uttype; switch (extension) { case ".png": uttype = "public.png"; break; case ".jpg": case ".jpeg": uttype = "public.jpeg"; break; default: throw new NotSupportedException(string.Format( "FramePixelData.Save cannot save images of type: {0}", extension)); } //var documentsDir = Environment.GetFolderPath (Environment.SpecialFolder.Personal); var handle = GCHandle.Alloc(_data, GCHandleType.Pinned); try { var sizeOfColor = Marshal.SizeOf(typeof(Color)); using (var dataProvider = new CGDataProvider( handle.AddrOfPinnedObject(), _data.Length * sizeOfColor, false)) using (var colorSpace = CGColorSpace.CreateDeviceRGB()) using (var image = new CGImage( Width, Height, 8, 32, Width * sizeOfColor, colorSpace, CGBitmapFlags.ByteOrder32Little | CGBitmapFlags.First, dataProvider, null, false, CGColorRenderingIntent.Default)) { //var fullPath = Path.Combine (documentsDir, path); Directory.CreateDirectory(Path.GetDirectoryName(path)); var url = NSUrl.FromFilename(Path.GetFullPath(path)); var destination = CGImageDestination.FromUrl(url, uttype, 1); destination.AddImage(image, null); if (!destination.Close()) { throw new Exception(string.Format( "Failed to write the image to '{0}'", path)); } } } finally { handle.Free(); } }
public SKSurface CreateSurface(CGRect contentsBounds, nfloat scale, out SKImageInfo info) { // apply a scale contentsBounds.Width *= scale; contentsBounds.Height *= scale; // get context details Info = info = CreateInfo((int)contentsBounds.Width, (int)contentsBounds.Height); // if there are no pixels, clean up and return if (info.Width == 0 || info.Height == 0) { Dispose(); return(null); } // if the memory size has changed, then reset the underlying memory if (bitmapData?.Length != (nuint)info.BytesSize) { FreeBitmap(); } // allocate a memory block for the drawing process if (bitmapData == null) { bitmapData = NSMutableData.FromLength(info.BytesSize); // in case allocation has failed if (bitmapData == null) { Dispose(); info = Info; return(null); } dataProvider = new CGDataProvider(bitmapData.MutableBytes, info.BytesSize, Dummy); void Dummy(IntPtr data) { // do nothing as we manage the memory separately } } return(SKSurface.Create(info, bitmapData.MutableBytes, info.RowBytes)); }
public bool ReadFile(String fileName, Mat mat, CvEnum.ImreadModes loadType) { try { using (CGDataProvider provider = new CGDataProvider(fileName)) using (CGImage tmp = CGImage.FromPNG(provider, null, false, CGColorRenderingIntent.Default)) { CGImageExtension.ConvertCGImageToArray(tmp, mat, loadType); } return(true); } catch (Exception e) { Debug.WriteLine(e); //throw; return(false); } }
internal static CGImage GetImage(this CGBitmapContext bitmapContext) { var provider = new CGDataProvider(bitmapContext.Data, bitmapContext.BytesPerRow * bitmapContext.Height, true); var NativeCGImage = new CGImage(bitmapContext.Width, bitmapContext.Height, bitmapContext.BitsPerComponent, bitmapContext.BitsPerPixel, bitmapContext.BytesPerRow, bitmapContext.ColorSpace, (CGBitmapFlags)bitmapContext.BitmapInfo, provider, null, false, CGColorRenderingIntent.Default); return(NativeCGImage); }
public override void ViewDidLoad () { base.ViewDidLoad (); var w = 100; var h = 100; var componentNum = 4; // RGBA var bytesPerRow = w * componentNum; var bitsPerComponent = 8; var data = new byte [bytesPerRow * h]; for (int x = 0; x < 100; x++) { for (int y = 0; y < 100; y++) { data [y * bytesPerRow + componentNum * x + 3] = 255; } } var provider = new CGDataProvider (data); var img = new CGImage (w, h, bitsPerComponent, bitsPerComponent * componentNum, bytesPerRow, CGColorSpace.CreateDeviceRGB (), CGBitmapFlags.Last, provider, null, false, CGColorRenderingIntent.Default); MyImage.Image = new NSImage (img, new CGSize (w, h)); }
/// <summary> /// Saves the specified color data as an image using the specified encoding. /// </summary> /// <param name="data">An array containing the image's color data.</param> /// <param name="width">The width of the image in pixels.</param> /// <param name="height">The height of the image in pixels.</param> /// <param name="stream">The stream to which to save the image data.</param> /// <param name="encoder">A function which produces an encoded data stream for the image.</param> private unsafe void Save(Color[] data, Int32 width, Int32 height, Stream stream, Func<UIImage, NSData> encoder) { fixed (Color* pdata = data) { using (var cgColorSpace = CGColorSpace.CreateDeviceRGB()) using (var cgDataProvider = new CGDataProvider((IntPtr)pdata, sizeof(Color) * width * height, false)) using (var cgImage = new CGImage(width, height, 8, 32, width * 4, cgColorSpace, CGBitmapFlags.PremultipliedLast, cgDataProvider, null, false, CGColorRenderingIntent.Default)) { using (var img = UIImage.FromImage(cgImage)) { using (var imgData = encoder(img)) using (var imgStream = imgData.AsStream()) { imgStream.CopyTo(stream); } } } } }
public void Save (string path) { var extension = Path.GetExtension (path).ToLowerInvariant (); string uttype; switch (extension) { case ".png": uttype = "public.png"; break; case ".jpg": case ".jpeg": uttype = "public.jpeg"; break; default: throw new NotSupportedException(string.Format( "FramePixelData.Save cannot save images of type: {0}", extension)); } //var documentsDir = Environment.GetFolderPath (Environment.SpecialFolder.Personal); var handle = GCHandle.Alloc(_data, GCHandleType.Pinned); try { var sizeOfColor = Marshal.SizeOf(typeof(Color)); using (var dataProvider = new CGDataProvider( handle.AddrOfPinnedObject(), _data.Length * sizeOfColor, false)) using (var colorSpace = CGColorSpace.CreateDeviceRGB()) using (var image = new CGImage( Width, Height, 8, 32, Width * sizeOfColor, colorSpace, CGBitmapFlags.ByteOrder32Little | CGBitmapFlags.First, dataProvider, null, false, CGColorRenderingIntent.Default)) { //var fullPath = Path.Combine (documentsDir, path); Directory.CreateDirectory(Path.GetDirectoryName(path)); var url = NSUrl.FromFilename (Path.GetFullPath(path)); var destination = CGImageDestination.FromUrl(url, uttype, 1); destination.AddImage(image, null); if (!destination.Close()) throw new Exception (string.Format ( "Failed to write the image to '{0}'", path)); } } finally { handle.Free (); } }
/// <summary> /// Init this instance to /// </summary> public static void Init() { NControl.Controls.FontLoader.LoadFonts (AppDomain.CurrentDomain.GetAssemblies(), (fontName, s) => { var data = new byte[s.Length]; s.Read (data, 0, data.Length); var dataProvider = new CGDataProvider (data, 0, data.Length); var cgFont = CGFont.CreateFromProvider (dataProvider); NSError error; var registered = CTFontManager.RegisterGraphicsFont(cgFont, out error); if (!registered) { // If the error code is 105 then the font we are trying to register is already registered // We will not report this as an error. if (error.Code != 105) throw new ArgumentException("Error registering: " + fontName + " (" + error.LocalizedDescription + ")"); } }); }
public byte[] ToPng(CImageByte img) { var provider = new CGDataProvider(img.Bytes, 0, (int)img.Length); int bitsPerComponent = 8; int components = (int)img.Channel; int bitsPerPixel = components * bitsPerComponent; int bytesPerRow = (int)img.Stride; // Tip: When you create a bitmap graphics context, // you’ll get the best performance if you make sure the data and bytesPerRow are 16-byte aligned. bool shouldInterpolate = false; var colorSpace = CGColorSpace.CreateDeviceRGB(); var cgImage = new CGImage( (int)img.Width, (int)img.Height, bitsPerComponent, bitsPerPixel, bytesPerRow, colorSpace, CGImageAlphaInfo.PremultipliedLast, provider, null, shouldInterpolate, CGColorRenderingIntent.Default); var uimg = UIImage.FromImage(cgImage); Console.WriteLine("topng info: " + uimg.Size.ToString()); return uimg.AsPNG().ToArray(); }
public Bitmap(int width, int height, PixelFormat format) { int bitsPerComponent, bytesPerRow; CGColorSpace colorSpace; CGBitmapFlags bitmapInfo; bool premultiplied = false; int bitsPerPixel = 0; switch (format){ case PixelFormat.Format32bppPArgb: 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.None; break; default: throw new Exception ("Format not supported: " + format); } bytesPerRow = width * bitsPerPixel/bitsPerComponent; int size = bytesPerRow * height; bitmapBlock = Marshal.AllocHGlobal (size); var provider = new CGDataProvider (bitmapBlock, size, true); NativeCGImage = new CGImage (width, height, bitsPerComponent, bitsPerPixel, bytesPerRow, colorSpace, bitmapInfo, provider, null, false, CGColorRenderingIntent.Default); }
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)); } }
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(); }
static UIImage MakeUIImage(byte[] bytes, int width) { var provider = new CGDataProvider(bytes, 0, bytes.Length); int bitsPerComponent = 8; int components = 4; int height = bytes.Length / components / width; int bitsPerPixel = components * bitsPerComponent; int bytesPerRow = components * width; // Tip: When you create a bitmap graphics context, you’ll get the best performance if you make sure the data and bytesPerRow are 16-byte aligned. bool shouldInterpolate = false; var colorSpace = CGColorSpace.CreateDeviceRGB(); var cgImage = new CGImage(width, height, bitsPerComponent, bitsPerPixel, bytesPerRow, colorSpace, CGImageAlphaInfo.Last, provider, null, shouldInterpolate, CGColorRenderingIntent.Default); return UIImage.FromImage(cgImage); }
private static CGImage CGImageFromPNGFile (string filename) { var provider = new CGDataProvider (filename); return CGImage.FromPNG (provider, null, false, CGColorRenderingIntent.AbsoluteColorimetric); }
public static bool IsAESCryptoDataProvider(CGDataProvider dataProviderRef) { return IsAESCryptoDataProvider_ (dataProviderRef.Handle); }
public static PSPDFDocument PDFDocumentWithDataProvider(CGDataProvider dataProvider) { return DocumentWithDataProvider_(dataProvider.Handle); }
public PSPDFDocumentProvider(CGDataProvider dataProvider, PSPDFDocument document) : this(dataProvider.Handle, document) { }
internal CGBitmapContext GetRenderableContext() { if (cachedContext != null && cachedContext.Handle != IntPtr.Zero) return cachedContext; var format = GetBestSupportedFormat (pixelFormat); var bitmapContext = CreateCompatibleBitmapContext ((int)NativeCGImage.Width, (int)NativeCGImage.Height, format); 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); CGColorSpace colorSpace = CGColorSpace.CreateDeviceRGB(); NativeCGImage = new CGImage ((int)bitmapContext.Width, (int)bitmapContext.Height, (int)bitmapContext.BitsPerComponent, (int)bitmapContext.BitsPerPixel, (int)bitmapContext.BytesPerRow, colorSpace, bitmapContext.AlphaInfo, provider, null, true, CGColorRenderingIntent.Default); colorSpace.Dispose (); cachedContext = bitmapContext; return cachedContext; }
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; }
private void MakeSureWeHaveAnAlphaChannel() { // Initialize our prmultiplied tables. if (!ConversionHelpers.sTablesInitialized) ConversionHelpers.CalculateTables (); var alphaInfo = NativeCGImage.AlphaInfo; var hasAlpha = ((alphaInfo == CGImageAlphaInfo.PremultipliedLast) || (alphaInfo == CGImageAlphaInfo.PremultipliedFirst) || (alphaInfo == CGImageAlphaInfo.Last) || (alphaInfo == CGImageAlphaInfo.First) ? true : false); if (cachedContext != null && cachedContext.Handle != IntPtr.Zero) { return; } // set our pixel format pixelFormat = PixelFormat.Format32bppArgb; // and mark the rawformat as from memory rawFormat = ImageFormat.MemoryBmp; //format = GetBestSupportedFormat (pixelFormat); cachedContext = CreateCompatibleBitmapContext ((int)NativeCGImage.Width, (int)NativeCGImage.Height, pixelFormat); // Fill our pixel data with the actual image information cachedContext.DrawImage (new CGRect (0, 0, (int)NativeCGImage.Width, (int)NativeCGImage.Height), NativeCGImage); // Dispose of the prevous image that is allocated. NativeCGImage.Dispose (); // Get a reference to the pixel data bitmapBlock = cachedContext.Data; int size = (int)(cachedContext.BytesPerRow * cachedContext.Height); var provider = new CGDataProvider (cachedContext.Data, size, true); // Get the image from the bitmap context. //NativeCGImage = bitmapContext.ToImage (); CGColorSpace colorSpace = CGColorSpace.CreateDeviceRGB(); NativeCGImage = new CGImage ((int)cachedContext.Width, (int)cachedContext.Height, (int)cachedContext.BitsPerComponent, (int)cachedContext.BitsPerPixel, (int)cachedContext.BytesPerRow, colorSpace, cachedContext.AlphaInfo, provider, null, true, CGColorRenderingIntent.Default); colorSpace.Dispose (); }
public IImage LoadImage(string path) { var provider = new CGDataProvider (path); CGImage image; if (System.IO.Path.GetExtension (path).ToLowerInvariant () == ".png") { image = CGImage.FromPNG (provider, null, false, CGColorRenderingIntent.Default); } else { image = CGImage.FromJPEG (provider, null, false, CGColorRenderingIntent.Default); } return new CGImageImage (image, 1); }
public UIImage Capture() { // This is from: https://developer.apple.com/library/ios/#qa/qa2010/qa1704.html int backingWidth, backingHeight; // Bind the color renderbuffer used to render the OpenGL ES view // If your application only creates a single color renderbuffer which is already bound at this point, // this call is redundant, but it is needed if you're dealing with multiple renderbuffers. // Note, replace "_colorRenderbuffer" with the actual name of the renderbuffer object defined in your class. gl.BindRenderbuffer (All.RenderbufferOes, Renderbuffer); // Get the size of the backing CAEAGLLayer gl.GetRenderbufferParameter (All.RenderbufferOes, All.RenderbufferWidthOes, out backingWidth); gl.GetRenderbufferParameter (All.RenderbufferOes, All.RenderbufferHeightOes, out backingHeight); int width = backingWidth, height = backingHeight; int dataLength = width * height * 4; byte[] data = new byte [dataLength]; // Read pixel data from the framebuffer gl.PixelStore (All.PackAlignment, 4); gl.ReadPixels (0, 0, width, height, All.Rgba, All.UnsignedByte, data); // Create a CGImage with the pixel data // If your OpenGL ES content is opaque, use kCGImageAlphaNoneSkipLast to ignore the alpha channel // otherwise, use kCGImageAlphaPremultipliedLast using (var data_provider = new CGDataProvider (data, 0, data.Length)) { using (var colorspace = CGColorSpace.CreateDeviceRGB ()) { using (var iref = new CGImage (width, height, 8, 32, width * 4, colorspace, (CGImageAlphaInfo) ((int) CGBitmapFlags.ByteOrder32Big | (int) CGImageAlphaInfo.PremultipliedLast), data_provider, null, true, CGColorRenderingIntent.Default)) { // OpenGL ES measures data in PIXELS // Create a graphics context with the target size measured in POINTS int widthInPoints, heightInPoints; float scale = ContentScaleFactor; widthInPoints = (int) (width / scale); heightInPoints = (int) (height / scale); UIGraphics.BeginImageContextWithOptions (new System.Drawing.SizeF (widthInPoints, heightInPoints), false, scale); try { var cgcontext = UIGraphics.GetCurrentContext (); // UIKit coordinate system is upside down to GL/Quartz coordinate system // Flip the CGImage by rendering it to the flipped bitmap context // The size of the destination area is measured in POINTS cgcontext.SetBlendMode (CGBlendMode.Copy); cgcontext.DrawImage (new System.Drawing.RectangleF (0, 0, widthInPoints, heightInPoints), iref); // Retrieve the UIImage from the current context var image = UIGraphics.GetImageFromCurrentImageContext (); return image; } finally { UIGraphics.EndImageContext (); } } } } }
public static PSPDFDocument FromDataProvider(CGDataProvider dataProvider) { return FromDataProvider_ (dataProvider.Handle); }
public static bool IsAesCryptoDataProvider(CGDataProvider dataProvider) { return IsAESCryptoDataProvider (dataProvider.Handle); }
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); }
public Bitmap(Stream stream, bool useIcm) { if (stream == null) throw new ArgumentNullException ("Value can not be null"); // false: stream is owned by user code //nativeObject = InitFromStream (stream); // TODO // Use Image IO byte[] buffer; using(var memoryStream = new MemoryStream()) { stream.CopyTo(memoryStream); buffer = memoryStream.ToArray(); } dataProvider = new CGDataProvider(buffer, 0, buffer.Length); InitializeImageFrame (0); }
public PSPDFDocument InitWithDataProvider(CGDataProvider dataProvider) { return InitWithDataProvider_(dataProvider.Handle); }
public Bitmap(string filename) { if (filename == null) throw new ArgumentNullException ("Value can not be null"); try { // Use Image IO dataProvider = new CGDataProvider(filename); if (dataProvider == null) throw new FileNotFoundException ("File {0} not found.", filename); InitializeImageFrame (0); } catch (Exception exc) { throw new FileNotFoundException ("File {0} not found.", filename); } }
public bool isAESCryptoDataProvider(CGDataProvider dataProvider) { return IsAESCryptoDataProvider_ (dataProvider.Handle); }
void LoadFontFile(string fileName) { CTFont nativeFont; var dpiSize = 0; var ext = Path.GetExtension(fileName); if (!String.IsNullOrEmpty(ext)) { if (nativeFontDescriptors == null) nativeFontDescriptors = new Dictionary<string, CTFontDescriptor> (); //Try loading from Bundle first var fontName = fileName.Substring (0, fileName.Length - ext.Length); var pathForResource = NSBundle.MainBundle.PathForResource (fontName, ext.Substring(1)); NSUrl url; if (!string.IsNullOrEmpty(pathForResource)) url = NSUrl.FromFilename (pathForResource); else url = NSUrl.FromFilename (fileName); // We will not use CTFontManager.RegisterFontsForUrl (url, CTFontManagerScope.Process); // here. The reason is that there is no way we can be sure that the font can be created to // to identify the family name afterwards. So instead we will create a CGFont from a data provider. // create CTFont to obtain the CTFontDescriptor, store family name and font descriptor to be accessed // later. try { var dataProvider = new CGDataProvider (url.Path); var cgFont = CGFont.CreateFromProvider (dataProvider); try { nativeFont = new CTFont(cgFont, dpiSize, null); if (!nativeFontDescriptors.ContainsKey(nativeFont.FamilyName)) { nativeFontDescriptors.Add(nativeFont.FamilyName, nativeFont.GetFontDescriptor()); NSError error; var registered = CTFontManager.RegisterGraphicsFont(cgFont, out error); if (!registered) { // If the error code is 105 then the font we are trying to register is already registered // We will not report this as an error. if (error.Code != 105) throw new ArgumentException("Error registering: " + Path.GetFileName(fileName)); } } } catch { // note: MS throw the same exception FileNotFoundException if the file exists but isn't a valid font file throw new System.IO.FileNotFoundException (fileName); } } catch (Exception) { // note: MS throw the same exception FileNotFoundException if the file exists but isn't a valid font file throw new System.IO.FileNotFoundException (fileName); } } }