public void Render() { if (!_isDirty) { return; } if (!IsEnabled) { return; } _wicRenderTarget.BeginDraw(); _wicRenderTarget.Clear(_clearColor); _wicRenderTarget.DrawText(_text, _textFormat, _rect, _sceneColorBrush); _wicRenderTarget.EndDraw(); var bitmapLock = _wicBitmap.Lock(SharpDX.WIC.BitmapLockFlags.Read); DataStream stream; _immediateContext.MapSubresource(_renderTexture, 0, 0, MapMode.WriteDiscard, SharpDX.Direct3D11.MapFlags.None, out stream); stream.WriteRange(bitmapLock.Data.DataPointer, _bitmapSize); _immediateContext.UnmapSubresource(_renderTexture, 0); stream.Dispose(); bitmapLock.Dispose(); _isDirty = false; }
private Bitmap CreateOutputImage(Action <WicRenderTarget> action) { try { var bitmap = new Bitmap(deviceRes2D.WICImgFactory, OutputWidth, OutputHeight, global::SharpDX.WIC.PixelFormat.Format32bppPBGRA, BitmapCreateCacheOption.CacheOnDemand); using (var target = new WicRenderTarget(deviceRes2D.Factory2D, bitmap, new RenderTargetProperties() { DpiX = 96, DpiY = 96, MinLevel = FeatureLevel.Level_DEFAULT, PixelFormat = new global::SharpDX.Direct2D1.PixelFormat(global::SharpDX.DXGI.Format.Unknown, AlphaMode.Unknown) })) { target.Transform = Matrix3x2.Identity; target.BeginDraw(); action(target); target.EndDraw(); } return(bitmap); } catch { return(null); } }
public void OnRender(float framesPerSecond) { if (_isEnabled == false) { return; } if (fps != framesPerSecond) { fps = framesPerSecond; textString = string.Format("FPS: {0}\n{1}", fps.ToString("0.00", culture), _text); _wicRenderTarget.BeginDraw(); _wicRenderTarget.Clear(clearColor); _wicRenderTarget.DrawText(textString, _textFormat, rect, _sceneColorBrush); _wicRenderTarget.EndDraw(); var bitmapLock = _wicBitmap.Lock(SharpDX.WIC.BitmapLockFlags.Read); DataStream stream; _immediateContext.MapSubresource(_renderTexture, 0, 0, MapMode.WriteDiscard, SharpDX.Direct3D11.MapFlags.None, out stream); stream.WriteRange(bitmapLock.Data.DataPointer, _width * _height * 4); _immediateContext.UnmapSubresource(_renderTexture, 0); stream.Dispose(); bitmapLock.Dispose(); } }
public void Save(Stream systemStream, Direct2DImageFormat format, string text, string faceName, float fontSize, out int width, out int height) { #if BENCHMARK using (var handler = Benchmark.Instance.Start("DirectWrite", "Save")) #endif using (var layout = new TextLayout(factoryManager.DwFactory, text, new TextFormat(factoryManager.DwFactory, faceName, fontSize * 1.3f), 4000, 4000)) { width = (int)Math.Ceiling(layout.Metrics.WidthIncludingTrailingWhitespace); height = (int)Math.Ceiling(layout.Metrics.Height); using (var wicBitmap = new SharpDX.WIC.Bitmap(factoryManager.WicFactory, width, height, SharpDX.WIC.PixelFormat.Format32bppPRGBA, BitmapCreateCacheOption.CacheOnLoad)) { var renderTargetProperties = new RenderTargetProperties(RenderTargetType.Default, new SharpDX.Direct2D1.PixelFormat(Format.R8G8B8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Unknown), imageDpi, imageDpi, RenderTargetUsage.None, FeatureLevel.Level_DEFAULT); using (var renderTarget = new WicRenderTarget(factoryManager.D2DFactory, wicBitmap, renderTargetProperties)) using (var brush = new SolidColorBrush(renderTarget, SharpDX.Color.White)) using (var encoder = new BitmapEncoder(factoryManager.WicFactory, Direct2DConverter.ConvertImageFormat(format))) { renderTarget.BeginDraw(); renderTarget.Clear(new Color4(1, 1, 1, 0)); renderTarget.DrawTextLayout(Vector2.Zero, layout, brush); renderTarget.EndDraw(); var stream = new WICStream(factoryManager.WicFactory, systemStream); encoder.Initialize(stream); using (var bitmapFrameEncode = new BitmapFrameEncode(encoder)) { bitmapFrameEncode.Initialize(); bitmapFrameEncode.SetSize(width, height); bitmapFrameEncode.WriteSource(wicBitmap); bitmapFrameEncode.Commit(); } encoder.Commit(); } } } }
public static global::SharpDX.WIC.Bitmap CreateBitmapStream(IDevice2DResources deviceResources, int width, int height, Direct2DImageFormat imageType, Action <RenderTarget> drawingAction) { if (width <= 0 || height <= 0) { return(null); } var bitmap = new global::SharpDX.WIC.Bitmap(deviceResources.WICImgFactory, width, height, global::SharpDX.WIC.PixelFormat.Format32bppBGR, BitmapCreateCacheOption.CacheOnDemand); using (var target = new WicRenderTarget(deviceResources.Factory2D, bitmap, new RenderTargetProperties() { DpiX = 96, DpiY = 96, MinLevel = FeatureLevel.Level_DEFAULT, PixelFormat = new global::SharpDX.Direct2D1.PixelFormat(global::SharpDX.DXGI.Format.Unknown, AlphaMode.Unknown) })) { target.Transform = Matrix3x2.Identity; target.BeginDraw(); drawingAction(target); target.EndDraw(); } return(bitmap); }
private static void Main() { var wicFactory = new ImagingFactory(); var d2dFactory = new SharpDX.Direct2D1.Factory(); string filename = "output.jpg"; const int width = 512; const int height = 512; var rectangleGeometry = new RoundedRectangleGeometry(d2dFactory, new RoundedRectangle() { RadiusX = 32, RadiusY = 32, Rect = new RectangleF(128, 128, width - 128 * 2, height - 128 * 2) }); var wicBitmap = new Bitmap(wicFactory, width, height, SharpDX.WIC.PixelFormat.Format32bppBGR, BitmapCreateCacheOption.CacheOnLoad); var renderTargetProperties = new RenderTargetProperties(RenderTargetType.Default, new PixelFormat(Format.Unknown, AlphaMode.Unknown), 0, 0, RenderTargetUsage.None, FeatureLevel.Level_DEFAULT); var d2dRenderTarget = new WicRenderTarget(d2dFactory, wicBitmap, renderTargetProperties); var solidColorBrush = new SolidColorBrush(d2dRenderTarget, Color.White); d2dRenderTarget.BeginDraw(); d2dRenderTarget.Clear(Color.Black); d2dRenderTarget.FillGeometry(rectangleGeometry, solidColorBrush, null); d2dRenderTarget.EndDraw(); if (File.Exists(filename)) { File.Delete(filename); } var stream = new WICStream(wicFactory, filename, NativeFileAccess.Write); // Initialize a Jpeg encoder with this stream var encoder = new JpegBitmapEncoder(wicFactory); encoder.Initialize(stream); // Create a Frame encoder var bitmapFrameEncode = new BitmapFrameEncode(encoder); bitmapFrameEncode.Initialize(); bitmapFrameEncode.SetSize(width, height); var pixelFormatGuid = SharpDX.WIC.PixelFormat.FormatDontCare; bitmapFrameEncode.SetPixelFormat(ref pixelFormatGuid); bitmapFrameEncode.WriteSource(wicBitmap); bitmapFrameEncode.Commit(); encoder.Commit(); bitmapFrameEncode.Dispose(); encoder.Dispose(); stream.Dispose(); System.Diagnostics.Process.Start(Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, filename))); }
public Direct2DImageEncoder(int imageWidth, int imageHeight, int imageDpi) { this.imageWidth = imageWidth; this.imageHeight = imageHeight; factoryManager = new Direct2DFactoryManager(); wicBitmap = new SharpDX.WIC.Bitmap(factoryManager.WicFactory, imageWidth, imageHeight, SharpDX.WIC.PixelFormat.Format32bppBGR, BitmapCreateCacheOption.CacheOnLoad); var renderTargetProperties = new RenderTargetProperties(RenderTargetType.Default, new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.Unknown, AlphaMode.Unknown), imageDpi, imageDpi, RenderTargetUsage.None, FeatureLevel.Level_DEFAULT); renderTarget = new WicRenderTarget(factoryManager.D2DFactory, wicBitmap, renderTargetProperties); renderTarget.BeginDraw(); renderTarget.Clear(SharpDX.Color.Yellow); }
private unsafe byte *GetBitmapData(string s, out int stride) { FreeBitmapData(); var size = GetMeasureString(s); var w = (int)(Math.Ceiling(size.Width += 2)); var h = (int)(Math.Ceiling(size.Height += 2)); CreateBitmap(w, h); _renderTarget.BeginDraw(); _renderTarget.Clear(TransparentColor); _renderTarget.AntialiasMode = AntialiasMode.Aliased; textFormat.TextAlignment = TextAlignment.Center; _renderTarget.DrawText(s, textFormat, new RectangleF(0, 0, w, h), _brush); _renderTarget.EndDraw(); //SaveToFile(@"C:\Xamarin\Cocos2D-XNAGraphics\" + s + ".png"); // Calculate stride of source stride = _bitmap.Size.Width * 4; // Create data array to hold source pixel data //byte[] data = new byte[stride * _bitmap.Size.Height]; byte[] data = new byte[stride * _bitmap.Size.Height]; using (var datas = new DataStream(stride * _bitmap.Size.Height, true, true)) { _bitmap.CopyPixels(stride, datas); data = datas.ReadRange <byte>(data.Length); } ReleaseResources(); pinnedArray = GCHandle.Alloc(data, GCHandleType.Pinned); IntPtr pointer = pinnedArray.AddrOfPinnedObject(); return((byte *)pointer);; }
public RenderTarget Create(Factory factory, Graphics g, Map map) { var wicBitmap = new WICBitmap(_wicFactory, map.Size.Width, map.Size.Height, SharpDX.WIC.PixelFormat.Format32bppPBGRA, BitmapCreateCacheOption.CacheOnDemand); var rtp = new RenderTargetProperties(RenderTargetType.Default, new D2D1PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, AlphaMode.Premultiplied), 0, 0, RenderTargetUsage.None, FeatureLevel.Level_DEFAULT); var res = new WicRenderTarget(factory, wicBitmap, rtp) { Tag = wicBitmap }; res.BeginDraw(); res.Clear(SharpDX.Color.Transparent); return(res); }
public static MemoryStream CreateBitmapStream(IDevice2DResources deviceResources, int width, int height, Direct2DImageFormat imageType, Action <RenderTarget> drawingAction) { using (var bitmap = new global::SharpDX.WIC.Bitmap(deviceResources.WICImgFactory, (int)width, (int)height, global::SharpDX.WIC.PixelFormat.Format32bppBGR, BitmapCreateCacheOption.CacheOnDemand)) { using (var target = new WicRenderTarget(deviceResources.Factory2D, bitmap, new RenderTargetProperties() { DpiX = 96, DpiY = 96, MinLevel = FeatureLevel.Level_DEFAULT, PixelFormat = new global::SharpDX.Direct2D1.PixelFormat(global::SharpDX.DXGI.Format.Unknown, AlphaMode.Unknown) })) { target.Transform = Matrix3x2.Identity; target.BeginDraw(); drawingAction(target); target.EndDraw(); } var systemStream = new MemoryStream(); using (var stream = new WICStream(deviceResources.WICImgFactory, systemStream)) { using (var encoder = new BitmapEncoder(deviceResources.WICImgFactory, imageType.ToWICImageFormat())) { encoder.Initialize(stream); using (var frameEncoder = new BitmapFrameEncode(encoder)) { frameEncoder.Initialize(); frameEncoder.SetSize((int)width, (int)height); frameEncoder.WriteSource(bitmap); frameEncoder.Commit(); encoder.Commit(); return(systemStream); } } } } }
// // 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); }
public static SharpDX.Direct2D1.Bitmap RedrawRestNoteBitmapCache(RenderTarget renderTargetSource, Color color, DurationTypes durationType) { ImagingFactory factory = new ImagingFactory(); SharpDX.Direct2D1.Factory factory2 = new SharpDX.Direct2D1.Factory(); SharpDX.DirectWrite.Factory factory3 = new SharpDX.DirectWrite.Factory(); SharpDX.WIC.Bitmap wicBitmap = new SharpDX.WIC.Bitmap(factory, 0x20, 0x30, SharpDX.WIC.PixelFormat.Format32bppPBGRA, BitmapCreateCacheOption.CacheOnDemand); RenderTargetProperties renderTargetProperties = new RenderTargetProperties(RenderTargetType.Default, new SharpDX.Direct2D1.PixelFormat(Format.Unknown, SharpDX.Direct2D1.AlphaMode.Unknown), 0f, 0f, RenderTargetUsage.None, FeatureLevel.Level_DEFAULT); WicRenderTarget renderTarget = new WicRenderTarget(factory2, wicBitmap, renderTargetProperties); try { PointF[] pathPoints; renderTarget.BeginDraw(); renderTarget.Clear(new RawColor4?(Color.Transparent.ToRawColor4(1f))); RawVector2 pos = new RawVector2(18f, 44f); using (GraphicsPath path = new GraphicsPath()) { DurationTypes types = durationType; if (types <= DurationTypes.Eighth) { switch (types) { case DurationTypes.The32nd: pos = new RawVector2(pos.X, (pos.Y - (8f * (((float)McMeasure.StaveSpacing) / 2f))) + 3f); path.AddLine(pos.X, pos.Y, pos.X + 1.6f, pos.Y); path.AddLine(pos.X + 1.6f, pos.Y, (pos.X - 8f) + 2.4f, pos.Y + 41f); path.AddLine((float)((pos.X - 8f) + 2.4f), (float)(pos.Y + 41f), (float)((pos.X - 8f) - 0.8f), (float)(pos.Y + 41f)); path.AddLine((pos.X - 8f) - 0.8f, pos.Y + 41f, pos.X, pos.Y); DrawRestDotPart(renderTarget, pos, color); DrawRestDotPart(renderTarget, new RawVector2(pos.X - 2.2f, pos.Y + 11f), color); DrawRestDotPart(renderTarget, new RawVector2(pos.X - 4.4f, pos.Y + 22f), color); break; case DurationTypes.The16th: pos = new RawVector2(pos.X, (pos.Y - (6f * (((float)McMeasure.StaveSpacing) / 2f))) + 3f); path.AddLine(pos.X, pos.Y, pos.X + 1.6f, pos.Y); path.AddLine(pos.X + 1.6f, pos.Y, (pos.X - 8f) + 2.4f, pos.Y + 30f); path.AddLine((float)((pos.X - 8f) + 2.4f), (float)(pos.Y + 30f), (float)((pos.X - 8f) - 0.8f), (float)(pos.Y + 30f)); path.AddLine((pos.X - 8f) - 0.8f, pos.Y + 30f, pos.X, pos.Y); DrawRestDotPart(renderTarget, pos, color); DrawRestDotPart(renderTarget, new RawVector2(pos.X - 2.4f, pos.Y + 11f), color); break; case DurationTypes.Eighth: goto Label_06F6; } } else { switch (types) { case DurationTypes.Quarter: pos = new RawVector2(pos.X - 11f, pos.Y - (7f * (((float)McMeasure.StaveSpacing) / 2f))); path.AddLine(pos.X, pos.Y, pos.X + 7f, pos.Y + 9.5f); path.AddBezier((float)(pos.X + 7f), (float)(pos.Y + 9.5f), (float)(pos.X + 3f), (float)(pos.Y + 16f), (float)(pos.X + 3f), (float)(pos.Y + 16f), (float)(pos.X + 8f), (float)(pos.Y + 24f)); path.AddBezier((float)(pos.X + 8f), (float)(pos.Y + 24f), (float)(pos.X - 0f), (float)(pos.Y + 21f), (float)(pos.X - 1f), (float)(pos.Y + 26f), (float)(pos.X + 4f), (float)(pos.Y + 34f)); path.AddBezier((float)(pos.X + 4f), (float)(pos.Y + 34f), (float)(pos.X - 8f), (float)(pos.Y + 28f), (float)(pos.X - 4f), (float)(pos.Y + 17f), (float)(pos.X + 4.5f), (float)(pos.Y + 21f)); path.AddLine((float)(pos.X + 4.5f), (float)(pos.Y + 21f), (float)(pos.X - 1f), (float)(pos.Y + 14f)); path.AddBezier((float)(pos.X - 1f), (float)(pos.Y + 14f), (float)(pos.X + 3.5f), (float)(pos.Y + 11f), (float)(pos.X + 4f), (float)(pos.Y + 7f), (float)(pos.X - 1f), (float)(pos.Y + 2f)); goto Label_0AD7; case DurationTypes.Half: pos = new RawVector2(pos.X - 8f, pos.Y - (4f * (((float)McMeasure.StaveSpacing) / 2f))); path.AddLine(pos.X - 7f, pos.Y, pos.X + 7f, pos.Y); path.AddLine(pos.X + 7f, pos.Y, pos.X + 7f, pos.Y - 5f); path.AddLine((float)(pos.X + 7f), (float)(pos.Y - 5f), (float)(pos.X - 7f), (float)(pos.Y - 5f)); path.AddLine(pos.X - 7f, pos.Y - 5f, pos.X - 7f, pos.Y); path.AddLine(pos.X - 7f, pos.Y, pos.X - 10f, pos.Y); path.AddLine(pos.X - 10f, pos.Y, pos.X - 10f, pos.Y + 1f); path.AddLine((float)(pos.X - 10f), (float)(pos.Y + 1f), (float)(pos.X + 10f), (float)(pos.Y + 1f)); path.AddLine(pos.X + 10f, pos.Y + 1f, pos.X + 10f, pos.Y); goto Label_0AD7; } if (types == DurationTypes.Whole) { pos = new RawVector2(pos.X - 8f, pos.Y - (6f * (((float)McMeasure.StaveSpacing) / 2f))); path.AddLine(pos.X - 7f, pos.Y, pos.X + 7f, pos.Y); path.AddLine(pos.X + 7f, pos.Y, pos.X + 7f, pos.Y + 5f); path.AddLine((float)(pos.X + 7f), (float)(pos.Y + 5f), (float)(pos.X - 7f), (float)(pos.Y + 5f)); path.AddLine(pos.X - 7f, pos.Y + 5f, pos.X - 7f, pos.Y); path.AddLine(pos.X - 7f, pos.Y, pos.X - 10f, pos.Y); path.AddLine(pos.X - 10f, pos.Y, pos.X - 10f, pos.Y - 1f); path.AddLine((float)(pos.X - 10f), (float)(pos.Y - 1f), (float)(pos.X + 10f), (float)(pos.Y - 1f)); path.AddLine(pos.X + 10f, pos.Y - 1f, pos.X + 10f, pos.Y); } } goto Label_0AD7; Label_06F6: pos = new RawVector2(pos.X - 2f, (pos.Y - (6f * (((float)McMeasure.StaveSpacing) / 2f))) + 3f); path.AddLine(pos.X, pos.Y, pos.X + 1.6f, pos.Y); path.AddLine(pos.X + 1.6f, pos.Y, (pos.X - 8f) + 2.4f, pos.Y + 19f); path.AddLine((float)((pos.X - 8f) + 2.4f), (float)(pos.Y + 19f), (float)((pos.X - 8f) - 0.8f), (float)(pos.Y + 19f)); path.AddLine((pos.X - 8f) - 0.8f, pos.Y + 19f, pos.X, pos.Y); DrawRestDotPart(renderTarget, pos, color); Label_0AD7: path.Flatten(); pathPoints = path.PathPoints; path.Dispose(); } PathGeometry geometry = new PathGeometry(factory2); if (pathPoints.Length > 1) { GeometrySink sink = geometry.Open(); sink.SetSegmentFlags(PathSegment.ForceRoundLineJoin); sink.BeginFigure(new RawVector2(pathPoints[0].X, pathPoints[0].Y), FigureBegin.Filled); for (int i = 1; i < pathPoints.Length; i++) { sink.AddLine(new RawVector2(pathPoints[i].X, pathPoints[i].Y)); } sink.EndFigure(FigureEnd.Closed); sink.Close(); sink.Dispose(); } SolidColorBrush brush = new SolidColorBrush(renderTarget, color.ToRawColor4(1f)); renderTarget.FillGeometry(geometry, brush); brush.Dispose(); geometry.Dispose(); renderTarget.EndDraw(); } catch (Exception) { factory.Dispose(); factory2.Dispose(); factory3.Dispose(); wicBitmap.Dispose(); renderTarget.Dispose(); return(null); } SharpDX.Direct2D1.Bitmap bitmap2 = SharpDX.Direct2D1.Bitmap.FromWicBitmap(renderTargetSource, wicBitmap); factory.Dispose(); factory2.Dispose(); factory3.Dispose(); wicBitmap.Dispose(); renderTarget.Dispose(); return(bitmap2); }
/// <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; } }
public async static Task <MemoryStream> InterpolateImageMarkup(StorageFile imageFile, StorageFile markupFile) { try { var bitmap = new BitmapImage(); using (var strm = await imageFile.OpenAsync(FileAccessMode.Read)) { bitmap.SetSource(strm); } var width = bitmap.PixelWidth; var height = bitmap.PixelHeight; var pixelFormat = WicPixelFormat.Format32bppBGR; var wicFactory = new ImagingFactory2(); var markupFactory = new ImagingFactory2(); var dddFactory = new SharpDX.Direct2D1.Factory(); var dwFactory = new SharpDX.DirectWrite.Factory(); WicRenderTarget renderTarget; Bitmap wicBitmap; SharpDX.Direct3D11.Device defaultDevice = new SharpDX.Direct3D11.Device(DriverType.Hardware, DeviceCreationFlags.Debug | DeviceCreationFlags.BgraSupport); var device = defaultDevice.QueryInterface <SharpDX.Direct3D11.Device1>(); SharpDX.DXGI.Device2 dxgiDevice2 = device.QueryInterface <SharpDX.DXGI.Device2>(); SharpDX.Direct2D1.Device d2dDevice = new SharpDX.Direct2D1.Device(dxgiDevice2); // d2dContext = new SharpDX.Direct2D1.DeviceContext(d2dDevice, SharpDX.Direct2D1.DeviceContextOptions.None); using (var bitmapSource = LoadBitmap(wicFactory, imageFile.Path)) { wicBitmap = new Bitmap(wicFactory, bitmapSource, BitmapCreateCacheOption.CacheOnLoad); int pixelWidth = (int)(wicBitmap.Size.Width * DisplayProperties.LogicalDpi / 96.0); int pixelHeight = (int)(wicBitmap.Size.Height * DisplayProperties.LogicalDpi / 96.0); var renderTargetProperties = new RenderTargetProperties(RenderTargetType.Default, new D2DPixelFormat(Format.Unknown, AlphaMode.Unknown), 0, 0, RenderTargetUsage.None, SharpDX.Direct2D1.FeatureLevel.Level_DEFAULT); renderTarget = new WicRenderTarget(dddFactory, wicBitmap, renderTargetProperties) { TextAntialiasMode = SharpDX.Direct2D1.TextAntialiasMode.Cleartype }; } renderTarget.BeginDraw(); renderTarget.DrawBitmap(LoadBitmapFromContentFile(wicFactory, markupFile.Path, renderTarget), 1.0f, SharpDX.Direct2D1.BitmapInterpolationMode.NearestNeighbor, new SharpDX.RectangleF(30, 50, 100, 80)); //new RectangleF(width - 150, 0, width, height + 25), renderTarget.EndDraw(); var ms = new MemoryStream(); var stream = new WICStream(wicFactory, ms); BitmapEncoder encoder = null; if (imageFile.FileType == ".png") { encoder = new PngBitmapEncoder(wicFactory); } else if (imageFile.FileType == ".jpg") { encoder = new JpegBitmapEncoder(wicFactory); } encoder.Initialize(stream); var frameEncoder = new BitmapFrameEncode(encoder); frameEncoder.Initialize(); frameEncoder.SetSize(width, height); //frameEncoder.piPixelFormat = WicPixelFormat.FormatDontCare; frameEncoder.WriteSource(wicBitmap); frameEncoder.Commit(); encoder.Commit(); frameEncoder.Dispose(); encoder.Dispose(); stream.Dispose(); ms.Position = 0; return(ms); } catch (Exception) { throw; } }
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()); }
public dx_resources() { d3dDevice = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Hardware, SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport); wicFactory = new SharpDX.WIC.ImagingFactory(); d2dFactory = new SharpDX.Direct2D1.Factory(); Texture2DDescription colordesc = new Texture2DDescription { BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource, Format = Format.B8G8R8A8_UNorm, Width = 1, Height = 1, MipLevels = 1, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, OptionFlags = ResourceOptionFlags.Shared, CpuAccessFlags = CpuAccessFlags.None, ArraySize = 1 }; this.RenderTarget = new Texture2D(d3dDevice, colordesc); Surface surface = this.RenderTarget.QueryInterface <Surface>(); RenderTargetProperties rtp = new RenderTargetProperties(new SharpDX.Direct2D1.PixelFormat(Format.Unknown, SharpDX.Direct2D1.AlphaMode.Premultiplied)); d2d_render_target = new RenderTarget(d2dFactory, surface, rtp); //d2d_render_target.AntialiasMode = AntialiasMode.PerPrimitive; descriptor_image_plus = new SharpDX.Direct2D1.Bitmap[6]; int bitmap_index = 0; for (int width = 16; width <= 512; width *= 2) { SharpDX.WIC.Bitmap point_image_wic = new SharpDX.WIC.Bitmap(wicFactory, (int)width, (int)width, SharpDX.WIC.PixelFormat.Format32bppPBGRA, BitmapCreateCacheOption.CacheOnLoad); RenderTargetProperties renderTargetProperties = new RenderTargetProperties(RenderTargetType.Default, new SharpDX.Direct2D1.PixelFormat(Format.Unknown, AlphaMode.Unknown), 0, 0, RenderTargetUsage.None, FeatureLevel.Level_DEFAULT); WicRenderTarget d2dRenderTarget = new WicRenderTarget(d2dFactory, point_image_wic, renderTargetProperties); SolidColorBrush solidColorBrush = new SolidColorBrush(d2dRenderTarget, Color.Black); d2dRenderTarget.BeginDraw(); d2dRenderTarget.Clear(Color.Transparent); if (width >= 256) { d2dRenderTarget.DrawEllipse(new Ellipse(new Vector2(width / 2f, width / 2f), width / 2f - 2f, width / 2f - 2f), solidColorBrush, 2f); } else { d2dRenderTarget.DrawEllipse(new Ellipse(new Vector2(width / 2f, width / 2f), width / 2f - 2f, width / 2f - 2f), solidColorBrush, 1f); } d2dRenderTarget.EndDraw(); BitmapProperties props = new BitmapProperties(new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, AlphaMode.Premultiplied)); descriptor_image_plus[bitmap_index] = SharpDX.Direct2D1.Bitmap.FromWicBitmap(d2d_render_target, point_image_wic, props); solidColorBrush.Dispose(); d2dRenderTarget.Dispose(); bitmap_index++; } descriptor_image_minus = new SharpDX.Direct2D1.Bitmap[6]; bitmap_index = 0; for (int width = 16; width <= 512; width *= 2) { SharpDX.WIC.Bitmap point_image_wic = new SharpDX.WIC.Bitmap(wicFactory, (int)width, (int)width, SharpDX.WIC.PixelFormat.Format32bppPBGRA, BitmapCreateCacheOption.CacheOnLoad); RenderTargetProperties renderTargetProperties = new RenderTargetProperties(RenderTargetType.Default, new SharpDX.Direct2D1.PixelFormat(Format.Unknown, AlphaMode.Unknown), 0, 0, RenderTargetUsage.None, FeatureLevel.Level_DEFAULT); WicRenderTarget d2dRenderTarget = new WicRenderTarget(d2dFactory, point_image_wic, renderTargetProperties); SolidColorBrush solidColorBrush = new SolidColorBrush(d2dRenderTarget, Color.White); d2dRenderTarget.BeginDraw(); d2dRenderTarget.Clear(Color.Transparent); if (width >= 256) { d2dRenderTarget.DrawEllipse(new Ellipse(new Vector2(width / 2f, width / 2f), width / 2f - 2f, width / 2f - 2f), solidColorBrush, 2f); } else { d2dRenderTarget.DrawEllipse(new Ellipse(new Vector2(width / 2f, width / 2f), width / 2f - 2f, width / 2f - 2f), solidColorBrush, 1f); } d2dRenderTarget.EndDraw(); BitmapProperties props = new BitmapProperties(new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, AlphaMode.Premultiplied)); descriptor_image_minus[bitmap_index] = SharpDX.Direct2D1.Bitmap.FromWicBitmap(d2d_render_target, point_image_wic, props); solidColorBrush.Dispose(); d2dRenderTarget.Dispose(); bitmap_index++; } float point_size = 10; SharpDX.WIC.Bitmap wic_point_image = new SharpDX.WIC.Bitmap(wicFactory, (int)point_size, (int)point_size, SharpDX.WIC.PixelFormat.Format32bppPBGRA, BitmapCreateCacheOption.CacheOnLoad); RenderTargetProperties renderTargetProperties_point_image = new RenderTargetProperties(RenderTargetType.Default, new SharpDX.Direct2D1.PixelFormat(Format.Unknown, AlphaMode.Unknown), 0, 0, RenderTargetUsage.None, FeatureLevel.Level_DEFAULT); WicRenderTarget d2dRenderTarget_point = new WicRenderTarget(d2dFactory, wic_point_image, renderTargetProperties_point_image); SolidColorBrush solidColorBrush_point = new SolidColorBrush(d2dRenderTarget_point, new Color4(137f / 255f, 201f / 255f, 238f / 255f, 1f)); SolidColorBrush solidColorBrush_point2 = new SolidColorBrush(d2dRenderTarget_point, Color.Black); d2dRenderTarget_point.BeginDraw(); d2dRenderTarget_point.Clear(Color.Transparent); d2dRenderTarget_point.FillEllipse(new Ellipse(new Vector2(point_size / 2f, point_size / 2f), point_size / 2f - 2f, point_size / 2f - 2f), solidColorBrush_point); d2dRenderTarget_point.DrawEllipse(new Ellipse(new Vector2(point_size / 2f, point_size / 2f), point_size / 2f - 2f, point_size / 2f - 2f), solidColorBrush_point2); d2dRenderTarget_point.EndDraw(); BitmapProperties props_point = new BitmapProperties(new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, AlphaMode.Premultiplied)); point_image = SharpDX.Direct2D1.Bitmap.FromWicBitmap(d2d_render_target, wic_point_image, props_point); solidColorBrush_point2.Dispose(); solidColorBrush_point.Dispose(); d2dRenderTarget_point.Dispose(); surface.Dispose(); }
public static SharpDX.Direct2D1.Bitmap RedrawMiscNoteBitmapCache(RenderTarget renderTargetSource, Color color) { ImagingFactory factory = new ImagingFactory(); SharpDX.Direct2D1.Factory factory2 = new SharpDX.Direct2D1.Factory(); SharpDX.DirectWrite.Factory factory3 = new SharpDX.DirectWrite.Factory(); SharpDX.WIC.Bitmap wicBitmap = new SharpDX.WIC.Bitmap(factory, 0x10, 0x10, SharpDX.WIC.PixelFormat.Format32bppPBGRA, BitmapCreateCacheOption.CacheOnDemand); RenderTargetProperties renderTargetProperties = new RenderTargetProperties(RenderTargetType.Default, new SharpDX.Direct2D1.PixelFormat(Format.Unknown, SharpDX.Direct2D1.AlphaMode.Unknown), 0f, 0f, RenderTargetUsage.None, FeatureLevel.Level_DEFAULT); WicRenderTarget renderTarget = new WicRenderTarget(factory2, wicBitmap, renderTargetProperties); try { PointF[] pathPoints; renderTarget.BeginDraw(); renderTarget.Clear(new RawColor4?(Color.Transparent.ToRawColor4(1f))); RawVector2 vector = new RawVector2(8f, 8f); using (GraphicsPath path = new GraphicsPath()) { float num = vector.X - 6f; float num2 = vector.Y - 3f; path.AddLine((float)(num + 0f), (float)(num2 + 0f), (float)(num + 12f), (float)(num2 + 0f)); path.AddLine((float)(num + 12f), (float)(num2 + 0f), (float)(num + 12f), (float)(num2 + 6f)); path.AddLine((float)(num + 12f), (float)(num2 + 6f), (float)(num + 0f), (float)(num2 + 6f)); path.AddLine((float)(num + 0f), (float)(num2 + 6f), (float)(num + 0f), (float)(num2 + 0f)); path.Flatten(); pathPoints = path.PathPoints; path.Dispose(); } PathGeometry geometry = new PathGeometry(factory2); if (pathPoints.Length > 1) { GeometrySink sink = geometry.Open(); sink.SetSegmentFlags(PathSegment.ForceRoundLineJoin); sink.BeginFigure(new RawVector2(pathPoints[0].X, pathPoints[0].Y), FigureBegin.Filled); for (int i = 1; i < pathPoints.Length; i++) { sink.AddLine(new RawVector2(pathPoints[i].X, pathPoints[i].Y)); } sink.EndFigure(FigureEnd.Closed); sink.Close(); sink.Dispose(); } SolidColorBrush brush = new SolidColorBrush(renderTarget, color.ToRawColor4(1f)); renderTarget.FillGeometry(geometry, brush); brush.Dispose(); geometry.Dispose(); renderTarget.EndDraw(); } catch (Exception) { factory.Dispose(); factory2.Dispose(); factory3.Dispose(); wicBitmap.Dispose(); renderTarget.Dispose(); return(null); } SharpDX.Direct2D1.Bitmap bitmap2 = SharpDX.Direct2D1.Bitmap.FromWicBitmap(renderTargetSource, wicBitmap); factory.Dispose(); factory2.Dispose(); factory3.Dispose(); wicBitmap.Dispose(); renderTarget.Dispose(); return(bitmap2); }
// private static SharpDX.Direct2D1.DeviceContext d2dContext; public async static Task <MemoryStream> RenderStaticTextToBitmap(StorageFile imageFile) { var bitmap = new BitmapImage(); using (var strm = await imageFile.OpenAsync(FileAccessMode.Read)) { bitmap.SetSource(strm); } var width = bitmap.PixelWidth; var height = bitmap.PixelHeight; var pixelFormat = WicPixelFormat.Format32bppBGR; var wicFactory = new ImagingFactory2(); var dddFactory = new SharpDX.Direct2D1.Factory(); var dwFactory = new SharpDX.DirectWrite.Factory(); WicRenderTarget renderTarget; Bitmap wicBitmap; using (var bitmapSource = LoadBitmap(wicFactory, imageFile.Path)) { wicBitmap = new Bitmap(wicFactory, bitmapSource, BitmapCreateCacheOption.CacheOnLoad); int pixelWidth = (int)(wicBitmap.Size.Width * DisplayProperties.LogicalDpi / 96.0); int pixelHeight = (int)(wicBitmap.Size.Height * DisplayProperties.LogicalDpi / 96.0); var renderTargetProperties = new RenderTargetProperties(RenderTargetType.Default, new D2DPixelFormat(Format.Unknown, AlphaMode.Unknown), 0, 0, RenderTargetUsage.None, SharpDX.Direct2D1.FeatureLevel.Level_DEFAULT); renderTarget = new WicRenderTarget( dddFactory, wicBitmap, renderTargetProperties) { TextAntialiasMode = SharpDX.Direct2D1.TextAntialiasMode.Cleartype }; } renderTarget.BeginDraw(); var textFormat = new TextFormat(dwFactory, "Segoe UI Light", 25) { TextAlignment = SharpDX.DirectWrite.TextAlignment.Leading, ParagraphAlignment = ParagraphAlignment.Far }; var textBrush = new SharpDX.Direct2D1.SolidColorBrush( renderTarget, SharpDX.Color.DarkBlue); StringBuilder sb = new StringBuilder(); var dstamp = StampPersistData.Instance.DataStamp; sb.Append(dstamp.KMReading).Append("\n"); sb.Append(dstamp.DateOfFirstReg).Append("\n"); sb.Append(dstamp.Gps).Append("\n"); sb.Append(dstamp.VehRegNo).Append("\n"); sb.Append(dstamp.Make).Append("\n"); sb.Append(dstamp.CusName).Append("\n"); sb.Append(dstamp.InspectorName).Append("\n"); sb.Append(dstamp.CaseNo); renderTarget.DrawText( sb.ToString(), textFormat, new SharpDX.RectangleF(1, 1, width + 50, height + 25), textBrush); //new RectangleF(width - 150, 0, width, height + 25), renderTarget.EndDraw(); var ms = new MemoryStream(); var stream = new WICStream( wicFactory, ms); BitmapEncoder encoder = null; if (imageFile.FileType == ".png") { encoder = new PngBitmapEncoder(wicFactory); } else if (imageFile.FileType == ".jpg") { encoder = new JpegBitmapEncoder(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); }