/// <summary> /// 将 Direct2D 位图保存到文件中。 /// </summary> /// <param name="image">要保存的位图。</param> /// <param name="fileName">要保存的文件名。</param> public void SaveBitmapToFile(Bitmap image, string fileName) { using (ImagingFactory2 factory = new ImagingFactory2()) { using (WICStream stream = new WICStream(factory, fileName, NativeFileAccess.Write)) { using (BitmapEncoder encoder = new PngBitmapEncoder(factory)) { encoder.Initialize(stream); using (BitmapFrameEncode bitmapFrameEncode = new BitmapFrameEncode(encoder)) { bitmapFrameEncode.Initialize(); int width = image.PixelSize.Width; int height = image.PixelSize.Height; bitmapFrameEncode.SetSize(width, height); Guid wicPixelFormat = WICPixelFormat; bitmapFrameEncode.SetPixelFormat(ref wicPixelFormat); using (ImageEncoder imageEncoder = new ImageEncoder(factory, this.d2DDevice)) { imageEncoder.WriteFrame(image, bitmapFrameEncode, new ImageParameters(D2PixelFormat, 96, 96, 0, 0, width, height)); bitmapFrameEncode.Commit(); encoder.Commit(); } } } } } }
// Used for debugging purposes private void SaveToFile(string fileName) { using (var pStream = new WICStream(FactoryImaging, fileName, SharpDX.IO.NativeFileAccess.Write)) { //var format = SharpDX.WIC.PixelFormat.Format32bppPRGBA; var format = SharpDX.WIC.PixelFormat.FormatDontCare; //// Use InitializeFromFilename to write to a file. If there is need to write inside the memory, use InitializeFromMemory. var encodingFormat = BitmapEncoderGuids.Png; var encoder = new PngBitmapEncoder(FactoryImaging, pStream); // Create a Frame encoder var pFrameEncode = new BitmapFrameEncode(encoder); pFrameEncode.Initialize(); pFrameEncode.SetSize((int)_renderTarget.Size.Width, (int)_renderTarget.Size.Height); pFrameEncode.SetPixelFormat(ref format); pFrameEncode.WriteSource(_bitmap); pFrameEncode.Commit(); encoder.Commit(); } }
public static void Save(this Texture2D texture, IRandomAccessStream stream, DeviceManager deviceManager) { var textureCopy = new Texture2D(deviceManager.DeviceDirect3D, new Texture2DDescription { Width = (int)texture.Description.Width, Height = (int)texture.Description.Height, MipLevels = 1, ArraySize = 1, Format = texture.Description.Format, Usage = ResourceUsage.Staging, SampleDescription = new SampleDescription(1, 0), BindFlags = BindFlags.None, CpuAccessFlags = CpuAccessFlags.Read, OptionFlags = ResourceOptionFlags.None }); deviceManager.ContextDirect3D.CopyResource(texture, textureCopy); DataStream dataStream; var dataBox = deviceManager.ContextDirect3D.MapSubresource( textureCopy, 0, 0, MapMode.Read, SharpDX.Direct3D11.MapFlags.None, out dataStream); var dataRectangle = new DataRectangle { DataPointer = dataStream.DataPointer, Pitch = dataBox.RowPitch }; var bitmap = new Bitmap( deviceManager.WICFactory, textureCopy.Description.Width, textureCopy.Description.Height, PixelFormat.Format32bppBGRA, dataRectangle); using (var s = stream.AsStream()) { s.Position = 0; using (var bitmapEncoder = new PngBitmapEncoder(deviceManager.WICFactory, s)) { using (var bitmapFrameEncode = new BitmapFrameEncode(bitmapEncoder)) { bitmapFrameEncode.Initialize(); bitmapFrameEncode.SetSize(bitmap.Size.Width, bitmap.Size.Height); var pixelFormat = PixelFormat.FormatDontCare; bitmapFrameEncode.SetPixelFormat(ref pixelFormat); bitmapFrameEncode.WriteSource(bitmap); bitmapFrameEncode.Commit(); bitmapEncoder.Commit(); } } } deviceManager.ContextDirect3D.UnmapSubresource(textureCopy, 0); textureCopy.Dispose(); bitmap.Dispose(); }
public MemoryStream RenderToPngStream(FrameworkElement fe) { var width = (int)Math.Ceiling(fe.ActualWidth); var height = (int)Math.Ceiling(fe.ActualHeight); // pixel format with transparency/alpha channel and RGB values premultiplied by alpha var pixelFormat = WicPixelFormat.Format32bppPRGBA; // pixel format without transparency, but one that works with Cleartype antialiasing //var pixelFormat = WicPixelFormat.Format32bppBGR; var wicBitmap = new Bitmap( this.WicFactory, width, height, pixelFormat, BitmapCreateCacheOption.CacheOnLoad); var renderTargetProperties = new RenderTargetProperties( RenderTargetType.Default, new D2DPixelFormat(Format.R8G8B8A8_UNorm, AlphaMode.Premultiplied), //new D2DPixelFormat(Format.Unknown, AlphaMode.Unknown), // use this for non-alpha, cleartype antialiased text 0, 0, RenderTargetUsage.None, FeatureLevel.Level_DEFAULT); var renderTarget = new WicRenderTarget( this.D2DFactory, wicBitmap, renderTargetProperties) { //TextAntialiasMode = TextAntialiasMode.Cleartype // this only works with the pixel format with no alpha channel TextAntialiasMode = TextAntialiasMode.Grayscale // this is the best we can do for bitmaps with alpha channels }; Compose(renderTarget, fe); // TODO: There is no need to encode the bitmap to PNG - we could just copy the texture pixel buffer to a WriteableBitmap pixel buffer. var ms = new MemoryStream(); var stream = new WICStream( this.WicFactory, ms); var encoder = new PngBitmapEncoder(WicFactory); encoder.Initialize(stream); var frameEncoder = new BitmapFrameEncode(encoder); frameEncoder.Initialize(); frameEncoder.SetSize(width, height); var format = WicPixelFormat.Format32bppBGRA; //var format = WicPixelFormat.FormatDontCare; frameEncoder.SetPixelFormat(ref format); frameEncoder.WriteSource(wicBitmap); frameEncoder.Commit(); encoder.Commit(); frameEncoder.Dispose(); encoder.Dispose(); stream.Dispose(); ms.Position = 0; return(ms); }
private static void InternalSaveTexture(string path, int arraySlice, int mipSlice, ImagingFactory2 Factory, Texture2D textureCopy, DeviceContext context) { DataStream dataStream; var dataBox = context.MapSubresource( textureCopy, mipSlice, arraySlice, MapMode.Read, SharpDX.Direct3D11.MapFlags.None, out dataStream); DataRectangle dataRectangle = new DataRectangle { DataPointer = dataStream.DataPointer, Pitch = dataBox.RowPitch }; Guid m_PixelFormat = PixelFormat.Format64bppRGBAHalf; if (textureCopy.Description.Format == Format.R16G16_Float) { m_PixelFormat = PixelFormat.Format32bppGrayFloat; } if (textureCopy.Description.Format == Format.R8G8B8A8_UNorm) { m_PixelFormat = PixelFormat.Format32bppBGRA; } int mipSize = (int)(textureCopy.Description.Width * Math.Pow(0.5, mipSlice)); var bitmap = new Bitmap( Factory, mipSize, mipSize, m_PixelFormat, dataRectangle); using (var s = new FileStream(path, FileMode.OpenOrCreate)) {//CREATE s.Position = 0; using (var bitmapEncoder = new PngBitmapEncoder(Factory, s)) { using (var bitmapFrameEncode = new BitmapFrameEncode(bitmapEncoder)) { bitmapFrameEncode.Initialize(); bitmapFrameEncode.SetSize(bitmap.Size.Width, bitmap.Size.Height); var pixelFormat = PixelFormat.FormatDontCare; bitmapFrameEncode.SetPixelFormat(ref pixelFormat); bitmapFrameEncode.WriteSource(bitmap); bitmapFrameEncode.Commit(); bitmapEncoder.Commit(); } } } bitmap.Dispose(); context.UnmapSubresource(textureCopy, 0); }
public override void Save(Stream stream) { using (var encoder = new PngBitmapEncoder(Direct2D1Platform.ImagingFactory, stream)) using (var frame = new BitmapFrameEncode(encoder)) { frame.Initialize(); frame.WriteSource(WicImpl); frame.Commit(); encoder.Commit(); } }
public override void Save(Stream stream) { using (var encoder = new PngBitmapEncoder(Direct2D1Platform.ImagingFactory, stream)) using (var frame = new BitmapFrameEncode(encoder)) using (var bitmapSource = _direct2DBitmap.QueryInterface <BitmapSource>()) { frame.Initialize(); frame.WriteSource(bitmapSource); frame.Commit(); encoder.Commit(); } }
public override void Save(Stream stream) { PngBitmapEncoder encoder = new PngBitmapEncoder(_factory); encoder.Initialize(stream); BitmapFrameEncode frame = new BitmapFrameEncode(encoder); frame.Initialize(); frame.WriteSource(WicImpl); frame.Commit(); encoder.Commit(); }
public static void ExportTexture(DeviceResources resources, StorageFile textureFile, Texture2D texture) { var device = resources.D3DDevice; var context = resources.D3DDeviceContext; var textureToSave = texture; var outputTexture = new Texture2D(device, new Texture2DDescription { Width = textureToSave.Description.Width, Height = textureToSave.Description.Height, MipLevels = 1, ArraySize = 1, Format = textureToSave.Description.Format, Usage = ResourceUsage.Staging, SampleDescription = new SampleDescription(1, 0), BindFlags = BindFlags.None, CpuAccessFlags = CpuAccessFlags.Read, OptionFlags = ResourceOptionFlags.None }); context.CopyResource(textureToSave, outputTexture); var mappedResource = context.MapSubresource(outputTexture, 0, 0, MapMode.Read, SharpDX.Direct3D11.MapFlags.None, out var dataStream); var dataRectangle = new DataRectangle { DataPointer = dataStream.DataPointer, Pitch = mappedResource.RowPitch }; var imagingFactory = new ImagingFactory(); var bitmap = new Bitmap(imagingFactory, outputTexture.Description.Width, outputTexture.Description.Height, PixelFormat.Format32bppRGBA, dataRectangle); using (var stream = new MemoryStream()) using (var bitmapEncoder = new PngBitmapEncoder(imagingFactory, stream)) using (var bitmapFrame = new BitmapFrameEncode(bitmapEncoder)) { bitmapFrame.Initialize(); bitmapFrame.SetSize(bitmap.Size.Width, bitmap.Size.Height); var pixelFormat = PixelFormat.FormatDontCare; bitmapFrame.SetPixelFormat(ref pixelFormat); bitmapFrame.WriteSource(bitmap); bitmapFrame.Commit(); bitmapEncoder.Commit(); FileIO.WriteBytesAsync(textureFile, stream.ToArray()).AsTask().Wait(-1); } context.UnmapSubresource(outputTexture, 0); outputTexture.Dispose(); bitmap.Dispose(); }
public static void WritePngToStream(this Bitmap bitmap, Stream stream, int width = -1, int height = -1) { if (width <= 0) { width = bitmap.Size.Width; } if (height <= 0) { height = bitmap.Size.Height; } // ------------------------------------------------------ // Encode a PNG image // ------------------------------------------------------ // Create a WIC outputstream var wicStream = new WICStream(DXGraphicsService.FactoryImaging, stream); // Initialize a Jpeg encoder with this stream var encoder = new PngBitmapEncoder(DXGraphicsService.FactoryImaging); encoder.Initialize(wicStream); // Create a Frame encoder var bitmapFrameEncode = new BitmapFrameEncode(encoder); bitmapFrameEncode.Initialize(); bitmapFrameEncode.SetSize(width, height); Guid guid = PixelFormat.Format32bppRGBA; bitmapFrameEncode.SetPixelFormat(ref guid); bitmapFrameEncode.WriteSource(bitmap); // Commit changes bitmapFrameEncode.Commit(); encoder.Commit(); // Cleanup bitmapFrameEncode.Options.Dispose(); bitmapFrameEncode.Dispose(); encoder.Dispose(); wicStream.Dispose(); }
public void Save(string fileName) { if (Path.GetExtension(fileName) != ".png") { // Yeah, we need to support other formats. throw new NotSupportedException("Use PNG, stoopid."); } using (FileStream s = new FileStream(fileName, FileMode.Create)) { PngBitmapEncoder encoder = new PngBitmapEncoder(factory); encoder.Initialize(s); BitmapFrameEncode frame = new BitmapFrameEncode(encoder); frame.Initialize(); frame.WriteSource(this.WicImpl); frame.Commit(); encoder.Commit(); } }
// // http://stackoverflow.com/questions/9151615/how-does-one-use-a-memory-stream-instead-of-files-when-rendering-direct2d-images // // Identical to above SO question, except that we are rendering to MemoryStream because it was added to the API // private MemoryStream RenderStaticTextToBitmap() { var width = 400; var height = 100; var pixelFormat = WicPixelFormat.Format32bppBGR; var wicFactory = new ImagingFactory(); var dddFactory = new SharpDX.Direct2D1.Factory(); var dwFactory = new SharpDX.DirectWrite.Factory(); var wicBitmap = new Bitmap( wicFactory, width, height, pixelFormat, BitmapCreateCacheOption.CacheOnLoad); var renderTargetProperties = new RenderTargetProperties( RenderTargetType.Default, new D2DPixelFormat(Format.Unknown, AlphaMode.Unknown), 0, 0, RenderTargetUsage.None, FeatureLevel.Level_DEFAULT); var renderTarget = new WicRenderTarget( dddFactory, wicBitmap, renderTargetProperties) { TextAntialiasMode = TextAntialiasMode.Cleartype }; renderTarget.BeginDraw(); var textFormat = new TextFormat(dwFactory, "Consolas", 48) { TextAlignment = SharpDX.DirectWrite.TextAlignment.Center, ParagraphAlignment = ParagraphAlignment.Center }; var textBrush = new SharpDX.Direct2D1.SolidColorBrush( renderTarget, SharpDX.Colors.Blue); renderTarget.Clear(Colors.White); renderTarget.DrawText( "Hi, mom!", textFormat, new RectangleF(0, 0, width, height), textBrush); renderTarget.EndDraw(); var ms = new MemoryStream(); var stream = new WICStream( wicFactory, ms); var encoder = new PngBitmapEncoder(wicFactory); encoder.Initialize(stream); var frameEncoder = new BitmapFrameEncode(encoder); frameEncoder.Initialize(); frameEncoder.SetSize(width, height); frameEncoder.PixelFormat = WicPixelFormat.FormatDontCare; frameEncoder.WriteSource(wicBitmap); frameEncoder.Commit(); encoder.Commit(); frameEncoder.Dispose(); encoder.Dispose(); stream.Dispose(); ms.Position = 0; return(ms); }
private void SaveToFile(D3DX direct3D, Texture2D texture, Guid format) { var stream = new System.IO.FileStream("Output.png", System.IO.FileMode.Create); var textureTarget = texture; var textureCopy = new Texture2D(direct3D.Device, new Texture2DDescription { Width = (int)textureTarget.Description.Width, Height = (int)textureTarget.Description.Height, MipLevels = 1, ArraySize = 1, Format = textureTarget.Description.Format, Usage = ResourceUsage.Staging, SampleDescription = new SampleDescription(1, 0), BindFlags = BindFlags.None, CpuAccessFlags = CpuAccessFlags.Read, OptionFlags = ResourceOptionFlags.None }); direct3D.DeviceContext.CopyResource(textureTarget, textureCopy); var dataBox = direct3D.DeviceContext.MapSubresource( textureCopy, 0, 0, MapMode.Read, SharpDX.Direct3D11.MapFlags.None, out DataStream dataStream); var dataRectangle = new DataRectangle { DataPointer = dataStream.DataPointer, Pitch = dataBox.RowPitch }; var imagingFactory = new ImagingFactory2(); var bitmap = new SharpDX.WIC.Bitmap( imagingFactory, textureCopy.Description.Width, textureCopy.Description.Height, format, dataRectangle); using (var s = stream) { s.Position = 0; using (var bitmapEncoder = new PngBitmapEncoder(imagingFactory, s)) { using (var bitmapFrameEncode = new BitmapFrameEncode(bitmapEncoder)) { bitmapFrameEncode.Initialize(); bitmapFrameEncode.SetSize(bitmap.Size.Width, bitmap.Size.Height); var pixelFormat = SharpDX.WIC.PixelFormat.FormatDontCare; bitmapFrameEncode.SetPixelFormat(ref pixelFormat); bitmapFrameEncode.WriteSource(bitmap); bitmapFrameEncode.Commit(); bitmapEncoder.Commit(); bitmapFrameEncode.Dispose(); bitmapEncoder.Dispose(); } } } direct3D.DeviceContext.UnmapSubresource(textureCopy, 0); textureCopy.Dispose(); bitmap.Dispose(); imagingFactory.Dispose(); dataStream.Dispose(); stream.Dispose(); }
/// <summary> /// 从rss生成图像 /// </summary> /// <param name="channel">从rss源获得的数据</param> /// <param name="path">保存图像的路径</param> private void GetImageFromRss(object obj) { ImageObj image = (ImageObj)obj; RssInfo rssInfo = image.rssInfo; RssMedia rssMedia = image.rssMedia; string fileName = ""; if (rssInfo == null || rssMedia == null) { return; } List <Page> pages = GetPageListFromRss(rssInfo, rssMedia); var wicFactory = new ImagingFactory(); var d2dFactory = new SharpDX.Direct2D1.Factory(); var dwFactory = new SharpDX.DirectWrite.Factory(); var renderTargetProperties = new RenderTargetProperties(RenderTargetType.Default, new SharpDX.Direct2D1.PixelFormat(Format.Unknown, SharpDX.Direct2D1.AlphaMode.Unknown), 0, 0, RenderTargetUsage.None, FeatureLevel.Level_DEFAULT); var wicBitmap = new SharpDX.WIC.Bitmap(wicFactory, pageWidth, pageHeight, SharpDX.WIC.PixelFormat.Format32bppBGR, BitmapCreateCacheOption.CacheOnLoad); var d2dRenderTarget = new WicRenderTarget(d2dFactory, wicBitmap, renderTargetProperties); d2dRenderTarget.AntialiasMode = AntialiasMode.PerPrimitive; var solidColorBrush = new SolidColorBrush(d2dRenderTarget, new SharpDX.Color(this.backgroundColor.R, this.backgroundColor.G, this.backgroundColor.B, this.backgroundColor.A)); var textBodyBrush = new SolidColorBrush(d2dRenderTarget, new SharpDX.Color(rssMedia.RssBodyProp. TextColor.R, rssMedia.RssBodyProp.TextColor.G, rssMedia.RssBodyProp.TextColor.B, rssMedia.RssBodyProp.TextColor.A)); var titleColorBrush = new SolidColorBrush(d2dRenderTarget, new SharpDX.Color(rssMedia.RssTitleProp.TextColor.R, rssMedia.RssTitleProp.TextColor.G, rssMedia.RssTitleProp.TextColor.B, rssMedia.RssTitleProp.TextColor.A)); var publishDateColorBrush = new SolidColorBrush(d2dRenderTarget, new SharpDX.Color(rssMedia.RssPublishTimeProp.TextColor.R, rssMedia.RssPublishTimeProp.TextColor.G, rssMedia.RssPublishTimeProp.TextColor.B, rssMedia.RssPublishTimeProp.TextColor.A)); TextLayout textLayout; try { int count = 0; foreach (Page page in pages) { d2dRenderTarget.BeginDraw(); d2dRenderTarget.Clear(new SharpDX.Color(this.backgroundColor.R, this.backgroundColor.G, this.backgroundColor.B, this.backgroundColor.A)); foreach (Line line in page.lines) { foreach (Block block in line.content) { TextFormat textFormat = new TextFormat(dwFactory, block.font.FontFamily.Name, block.font.Size); textLayout = new TextLayout(dwFactory, block.content, textFormat, block.width, block.height); switch (block.type) { case RssBodyType.Title: textLayout.SetUnderline(rssMedia.RssTitleProp.TextFont.Underline, new TextRange(0, block.content.Length)); textLayout.SetFontStyle(rssMedia.RssTitleProp.TextFont.Italic ? FontStyle.Italic : FontStyle.Normal, new TextRange(0, block.content.Length)); textLayout.SetFontWeight(rssMedia.RssTitleProp.TextFont.Bold ? FontWeight.Bold : FontWeight.Normal, new TextRange(0, block.content.Length)); d2dRenderTarget.DrawTextLayout(new Vector2(block.left, block.top), textLayout, titleColorBrush); break; case RssBodyType.Time: textLayout.SetUnderline(rssMedia.RssPublishTimeProp.TextFont.Underline, new TextRange(0, block.content.Length)); textLayout.SetFontStyle(rssMedia.RssPublishTimeProp.TextFont.Italic ? FontStyle.Italic : FontStyle.Normal, new TextRange(0, block.content.Length)); textLayout.SetFontWeight(rssMedia.RssPublishTimeProp.TextFont.Bold ? FontWeight.Bold : FontWeight.Normal, new TextRange(0, block.content.Length)); d2dRenderTarget.DrawTextLayout(new Vector2(block.left, block.top), textLayout, publishDateColorBrush); break; case RssBodyType.Body: textLayout.SetUnderline(rssMedia.RssBodyProp.TextFont.Underline, new TextRange(0, block.content.Length)); textLayout.SetFontStyle(rssMedia.RssBodyProp.TextFont.Italic ? FontStyle.Italic : FontStyle.Normal, new TextRange(0, block.content.Length)); textLayout.SetFontWeight(rssMedia.RssBodyProp.TextFont.Bold ? FontWeight.Bold : FontWeight.Normal, new TextRange(0, block.content.Length)); d2dRenderTarget.DrawTextLayout(new Vector2(block.left, block.top), textLayout, textBodyBrush); break; default: break; } textFormat.Dispose(); textFormat = null; } } d2dRenderTarget.EndDraw(); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } fileName = string.Format("{0}{1}.jpg", path, DateTime.Now.Ticks.ToString()); var stream = new WICStream(wicFactory, fileName, NativeFileAccess.Write); var encoder = new PngBitmapEncoder(wicFactory); encoder.Initialize(stream); var bitmapFrameEncode = new BitmapFrameEncode(encoder); bitmapFrameEncode.Initialize(); bitmapFrameEncode.SetSize(pageWidth, pageHeight); var pixelFormatGuid = SharpDX.WIC.PixelFormat.FormatDontCare; bitmapFrameEncode.SetPixelFormat(ref pixelFormatGuid); bitmapFrameEncode.WriteSource(wicBitmap); bitmapFrameEncode.Commit(); encoder.Commit(); bitmapFrameEncode.Dispose(); encoder.Dispose(); stream.Dispose(); Console.WriteLine("*********image count is : " + count++); //发送单个图片生成事件 if (SingleGenerateCompleteEvent != null) { SingleGenerateCompleteEvent(fileName); } } //发送生成完成事件 if (GenerateCompleteEvent != null) { GenerateCompleteEvent(path); //停止线程,从字典删除 StopGenerate(rssMedia.CachePath); } } catch (ThreadAbortException aborted) { Trace.WriteLine("rss 图片生成线程终止 : " + aborted.Message); } catch (Exception ex) { Trace.WriteLine("rss 图片生成遇到bug : " + ex.Message); } finally { wicFactory.Dispose(); d2dFactory.Dispose(); dwFactory.Dispose(); wicBitmap.Dispose(); d2dRenderTarget.Dispose(); solidColorBrush.Dispose(); textBodyBrush.Dispose(); titleColorBrush.Dispose(); publishDateColorBrush.Dispose(); rssInfo.Dispose(); rssMedia.Dispose(); wicFactory = null; d2dFactory = null; dwFactory = null; wicBitmap = null; d2dRenderTarget = null; solidColorBrush = null; textBodyBrush = null; titleColorBrush = null; publishDateColorBrush = null; rssInfo = null; rssMedia = null; pages.Clear(); pages = null; } }
internal CCTexture2D CreateTextSprite(string text, CCFontDefinition textDefinition) { if (string.IsNullOrEmpty(text)) { return(new CCTexture2D()); } int imageWidth; int imageHeight; var textDef = textDefinition; var contentScaleFactorWidth = CCLabel.DefaultTexelToContentSizeRatios.Width; var contentScaleFactorHeight = CCLabel.DefaultTexelToContentSizeRatios.Height; textDef.FontSize *= (int)contentScaleFactorWidth; textDef.Dimensions.Width *= contentScaleFactorWidth; textDef.Dimensions.Height *= contentScaleFactorHeight; bool hasPremultipliedAlpha; var font = CreateFont(textDef.FontName, textDef.FontSize); var _currentFontSizeEm = textDef.FontSize; var _currentDIP = ConvertPointSizeToDIP(_currentFontSizeEm); var fontColor = textDef.FontFillColor; var fontAlpha = textDef.FontAlpha; var foregroundColor = new Color4(fontColor.R / 255.0f, fontColor.G / 255.0f, fontColor.B / 255.0f, fontAlpha / 255.0f); // alignment var horizontalAlignment = textDef.Alignment; var verticleAlignement = textDef.LineAlignment; var textAlign = (CCTextAlignment.Right == horizontalAlignment) ? TextAlignment.Trailing : (CCTextAlignment.Center == horizontalAlignment) ? TextAlignment.Center : TextAlignment.Leading; var paragraphAlign = (CCVerticalTextAlignment.Bottom == vertAlignment) ? ParagraphAlignment.Far : (CCVerticalTextAlignment.Center == vertAlignment) ? ParagraphAlignment.Center : ParagraphAlignment.Near; // LineBreak var lineBreak = (CCLabelLineBreak.Character == textDef.LineBreak) ? WordWrapping.Wrap : (CCLabelLineBreak.Word == textDef.LineBreak) ? WordWrapping.Wrap : WordWrapping.NoWrap; // LineBreak // TODO: Find a way to specify the type of line breaking if possible. var dimensions = new CCSize(textDef.Dimensions.Width, textDef.Dimensions.Height); var layoutAvailable = true; if (dimensions.Width <= 0) { dimensions.Width = 8388608; layoutAvailable = false; } if (dimensions.Height <= 0) { dimensions.Height = 8388608; layoutAvailable = false; } var fontName = font.FontFamily.FamilyNames.GetString(0); var textFormat = new TextFormat(FactoryDWrite, fontName, _currentFontCollection, FontWeight.Regular, FontStyle.Normal, FontStretch.Normal, _currentDIP); textFormat.TextAlignment = textAlign; textFormat.ParagraphAlignment = paragraphAlign; var textLayout = new TextLayout(FactoryDWrite, text, textFormat, dimensions.Width, dimensions.Height); var boundingRect = new RectangleF(); // Loop through all the lines so we can find our drawing offsets var textMetrics = textLayout.Metrics; var lineCount = textMetrics.LineCount; // early out if something went wrong somewhere and nothing is to be drawn if (lineCount == 0) { return(new CCTexture2D()); } // Fill out the bounding rect width and height so we can calculate the yOffset later if needed boundingRect.X = 0; boundingRect.Y = 0; boundingRect.Width = textMetrics.Width; boundingRect.Height = textMetrics.Height; if (!layoutAvailable) { if (dimensions.Width == 8388608) { dimensions.Width = boundingRect.Width; } if (dimensions.Height == 8388608) { dimensions.Height = boundingRect.Height; } } imageWidth = (int)dimensions.Width; imageHeight = (int)dimensions.Height; // Recreate our layout based on calculated dimensions so that we can draw the text correctly // in our image when Alignment is not Left. if (textAlign != TextAlignment.Leading) { textLayout.MaxWidth = dimensions.Width; textLayout.MaxHeight = dimensions.Height; } // Line alignment var yOffset = (CCVerticalTextAlignment.Bottom == verticleAlignement || boundingRect.Bottom >= dimensions.Height) ? dimensions.Height - boundingRect.Bottom // align to bottom : (CCVerticalTextAlignment.Top == verticleAlignement) ? 0 // align to top : (imageHeight - boundingRect.Bottom) * 0.5f; // align to center SharpDX.WIC.Bitmap sharpBitmap = null; WicRenderTarget sharpRenderTarget = null; SolidColorBrush solidBrush = null; try { // Select our pixel format var pixelFormat = SharpDX.WIC.PixelFormat.Format32bppPRGBA; // create our backing bitmap sharpBitmap = new SharpDX.WIC.Bitmap(FactoryImaging, imageWidth, imageHeight, pixelFormat, BitmapCreateCacheOption.CacheOnLoad); // Create the render target that we will draw to sharpRenderTarget = new WicRenderTarget(Factory2D, sharpBitmap, new RenderTargetProperties()); // Create our brush to actually draw with solidBrush = new SolidColorBrush(sharpRenderTarget, foregroundColor); // Begin the drawing sharpRenderTarget.BeginDraw(); if (textDefinition.isShouldAntialias) { sharpRenderTarget.AntialiasMode = AntialiasMode.Aliased; } // Clear it sharpRenderTarget.Clear(TransparentColor); // Draw the text to the bitmap sharpRenderTarget.DrawTextLayout(new Vector2(boundingRect.X, yOffset), textLayout, solidBrush); // End our drawing which will commit the rendertarget to the bitmap sharpRenderTarget.EndDraw(); // Debugging purposes //var s = "Label4"; //SaveToFile(@"C:\Xamarin\" + s + ".png", _bitmap, _renderTarget); // The following code creates a .png stream in memory of our Bitmap and uses it to create our Textue2D Texture2D tex = null; using (var memStream = new MemoryStream()) { using (var encoder = new PngBitmapEncoder(FactoryImaging, memStream)) using (var frameEncoder = new BitmapFrameEncode(encoder)) { frameEncoder.Initialize(); frameEncoder.WriteSource(sharpBitmap); frameEncoder.Commit(); encoder.Commit(); } // Create the Texture2D from the png stream tex = Texture2D.FromStream(CCDrawManager.SharedDrawManager.XnaGraphicsDevice, memStream); } // Return our new CCTexture2D created from the Texture2D which will have our text drawn on it. return(new CCTexture2D(tex)); } catch (Exception exc) { CCLog.Log("CCLabel-Windows: Unable to create the backing image of our text. Message: {0}", exc.StackTrace); } finally { if (sharpBitmap != null) { sharpBitmap.Dispose(); sharpBitmap = null; } if (sharpRenderTarget != null) { sharpRenderTarget.Dispose(); sharpRenderTarget = null; } if (solidBrush != null) { solidBrush.Dispose(); solidBrush = null; } if (textFormat != null) { textFormat.Dispose(); textFormat = null; } if (textLayout != null) { textLayout.Dispose(); textLayout = null; } } // If we have reached here then something has gone wrong. return(new CCTexture2D()); }
//create a bitmap from a texture2D. DOES NOT WORK public static System.Drawing.Bitmap GetTextureBitmap(Device device, Texture2D tex, int mipSlice) { int w = tex.Description.Width; int h = tex.Description.Height; var textureCopy = new Texture2D(device, new Texture2DDescription { Width = w, Height = h, MipLevels = tex.Description.MipLevels, ArraySize = 1, Format = SharpDX.DXGI.Format.R8G8B8A8_UNorm, Usage = ResourceUsage.Staging, SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0), BindFlags = BindFlags.None, CpuAccessFlags = CpuAccessFlags.Read, OptionFlags = ResourceOptionFlags.None }); DataStream dataStream;// = new DataStream(8 * tex.Description.Width * tex.Description.Height, true, true); DeviceContext context = device.ImmediateContext; //context.CopyResource(tex, textureCopy); context.CopySubresourceRegion(tex, mipSlice, null, textureCopy, 0); var dataBox = context.MapSubresource( textureCopy, mipSlice, 0, MapMode.Read, SharpDX.Direct3D11.MapFlags.None, out dataStream); //int bytesize = w * h * 4; //byte[] pixels = new byte[bytesize]; //dataStream.Read(pixels, 0, bytesize); //dataStream.Position = 0; var dataRectangle = new DataRectangle { DataPointer = dataStream.DataPointer, Pitch = dataBox.RowPitch }; ImagingFactory wicf = new ImagingFactory(); var b = new SharpDX.WIC.Bitmap(wicf, w, h, SharpDX.WIC.PixelFormat.Format32bppBGRA, dataRectangle); var s = new MemoryStream(); using (var bitmapEncoder = new PngBitmapEncoder(wicf, s)) { using (var bitmapFrameEncode = new BitmapFrameEncode(bitmapEncoder)) { bitmapFrameEncode.Initialize(); bitmapFrameEncode.SetSize(b.Size.Width, b.Size.Height); var pixelFormat = PixelFormat.FormatDontCare; bitmapFrameEncode.SetPixelFormat(ref pixelFormat); bitmapFrameEncode.WriteSource(b); bitmapFrameEncode.Commit(); bitmapEncoder.Commit(); } } context.UnmapSubresource(textureCopy, 0); textureCopy.Dispose(); b.Dispose(); s.Position = 0; var bmp = new System.Drawing.Bitmap(s); //Palette pal = new Palette(wf); //b.CopyPalette(pal); //byte[] pixels = new byte[w * h * 4]; //b.CopyPixels(pixels, w * 4); //GCHandle handle = GCHandle.Alloc(pixels, GCHandleType.Pinned); //var hptr = handle.AddrOfPinnedObject(); //System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(w, h, w * 4, System.Drawing.Imaging.PixelFormat.Format32bppArgb, hptr); //handle.Free(); //System.Threading.Thread.Sleep(1000); //System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(w, h, System.Drawing.Imaging.PixelFormat.Format32bppPArgb); //System.Drawing.Imaging.BitmapData data = bmp.LockBits( // new System.Drawing.Rectangle(System.Drawing.Point.Empty, bmp.Size), // System.Drawing.Imaging.ImageLockMode.WriteOnly, // System.Drawing.Imaging.PixelFormat.Format32bppPArgb); ////b.CopyPixels(Int32Rect.Empty, data.Scan0, data.Height * data.Stride, data.Stride); //b.CopyPixels(data.Stride, data.Scan0, data.Height * data.Stride); //bmp.UnlockBits(data); var c1 = bmp.GetPixel(10, 2); //dataStream.Dispose(); return(bmp); }
public async Task <System.IO.MemoryStream> RenderLabelToStream( float imageWidth, float imageHeight, Color4 foregroundColor, Vector2 origin, TextLayout textLayout, float dpi = DEFAULT_DPI, SharpDX.DXGI.Format format = SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode alpha = AlphaMode.Premultiplied) { // Get stream var pngStream = new MemoryStream(); using (var renderTarget = RenderLabel( imageWidth, imageHeight, foregroundColor, origin, textLayout, dpi, format, alpha)) { pngStream.Position = 0; // Create a WIC outputstream using (var wicStream = new WICStream(FactoryImaging, pngStream)) { var size = renderTarget.PixelSize; // Initialize a Png encoder with this stream using (var wicBitmapEncoder = new PngBitmapEncoder(FactoryImaging, wicStream)) { // Create a Frame encoder using (var wicFrameEncoder = new BitmapFrameEncode(wicBitmapEncoder)) { wicFrameEncoder.Initialize(); // Create image encoder ImageEncoder wicImageEncoder; ImagingFactory2 factory2 = new ImagingFactory2(); wicImageEncoder = new ImageEncoder(factory2, D2DDevice); var imgParams = new ImageParameters(); imgParams.PixelFormat = new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, AlphaMode.Premultiplied); imgParams.PixelHeight = (int)size.Height; imgParams.PixelWidth = (int)size.Width; wicImageEncoder.WriteFrame(renderTarget, wicFrameEncoder, imgParams); //// Commit changes wicFrameEncoder.Commit(); wicBitmapEncoder.Commit(); byte[] buffer = new byte[pngStream.Length]; pngStream.Position = 0; await pngStream.ReadAsync(buffer, 0, (int)pngStream.Length); } } } } return(pngStream); }