public static void WatermarkText(Stream imageStream, Stream outputStream, string watermark, string font = "Times New Roman", float fontSize = 30.0f, int colorARGB = TransparentWhite) { using (var wic = new WIC.ImagingFactory2()) using (var d2d = new D2D.Factory()) using (var image = CreateWicImage(wic, imageStream)) using (var wicBitmap = new WIC.Bitmap(wic, image.Size.Width, image.Size.Height, WIC.PixelFormat.Format32bppPBGRA, WIC.BitmapCreateCacheOption.CacheOnDemand)) using (var target = new D2D.WicRenderTarget(d2d, wicBitmap, new D2D.RenderTargetProperties())) using (var bmpPicture = D2D.Bitmap.FromWicBitmap(target, image)) using (var dwriteFactory = new DWrite.Factory()) using (var brush = new D2D.SolidColorBrush(target, new Color(colorARGB))) { target.BeginDraw(); { target.DrawBitmap(bmpPicture, new RectangleF(0, 0, target.Size.Width, target.Size.Height), 1.0f, D2D.BitmapInterpolationMode.Linear); target.DrawRectangle(new RectangleF(0, 0, target.Size.Width, target.Size.Height), brush); var textFormat = new DWrite.TextFormat(dwriteFactory, font, DWrite.FontWeight.Bold, DWrite.FontStyle.Normal, fontSize) { ParagraphAlignment = DWrite.ParagraphAlignment.Far, TextAlignment = DWrite.TextAlignment.Trailing, }; target.DrawText(watermark, textFormat, new RectangleF(0, 0, target.Size.Width, target.Size.Height), brush); } target.EndDraw(); SaveD2DBitmap(wic, wicBitmap, outputStream); } }
public override void Dispose() { base.Dispose(); this.wicRenderTarget?.Dispose(); this.wicRenderTarget = null; System.Threading.Monitor.Exit(lockObj); }
private static void DrawSmallRaw(Person person, WIC.ImagingFactory wic, D2D.Factory d2dFactory, WIC.FormatConverter converter) { var whRate = 1.0f * converter.Size.Width / converter.Size.Height; var smallRawSize = new Vector2(whRate * ImageDefines.SmallRawY, ImageDefines.SmallRawY); var scale = ImageDefines.SmallRawY / converter.Size.Height; using (var wicBitmap = new WIC.Bitmap(wic, (int)smallRawSize.X, (int)smallRawSize.Y, WIC.PixelFormat.Format32bppPBGRA, WIC.BitmapCreateCacheOption.CacheOnDemand)) using (var target = new D2D.WicRenderTarget(d2dFactory, wicBitmap, new D2D.RenderTargetProperties())) using (var bmp = D2D.Bitmap.FromWicBitmap(target, converter)) using (var bmpBrush = new D2D.BitmapBrush(target, bmp)) { target.BeginDraw(); target.Transform = Matrix3x2.Scaling(scale, scale); target.DrawBitmap(bmp, 1.0f, D2D.BitmapInterpolationMode.Linear); target.EndDraw(); using (var file = File.Create(person.SmallRawImage)) { WicTools.SaveD2DBitmap(wic, wicBitmap, file); } } }
private RendererDirect2D Create(PxSize size, out WIC.Bitmap wicBitmap) { _bitmap = wicBitmap = new WIC.Bitmap( WicFactory, (int)(size.Width * 1.0f), (int)(size.Height * 1.0f), WIC.PixelFormat.Format32bppPBGRA, WIC.BitmapCreateCacheOption.CacheOnLoad ); wicBitmap.SetResolution(200, 200); var renderProps = new D2D1.RenderTargetProperties( D2D1.RenderTargetType.Default, new D2D1.PixelFormat( DXGI.Format.B8G8R8A8_UNorm, D2D1.AlphaMode.Premultiplied ), 96, 96, D2D1.RenderTargetUsage.None, //GdiCompatible| D2D1.RenderTargetUsage.ForceBitmapRemoting, D2D1.FeatureLevel.Level_DEFAULT ); var wicRenderTarget = new D2D1.WicRenderTarget( D2DFactory, wicBitmap, renderProps ); // {DotsPerInch = new Size2F(600, 600)}; return(new RendererDirect2D(this, wicRenderTarget)); }
void CreateRenderTarget() { var renderProp = new sd.RenderTargetProperties { DpiX = 0, DpiY = 0, MinLevel = sd.FeatureLevel.Level_DEFAULT, Type = sd.RenderTargetType.Default, Usage = sd.RenderTargetUsage.None }; if (drawable != null) { renderProp.PixelFormat = new sd.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, sd.AlphaMode.Premultiplied); var winProp = new sd.HwndRenderTargetProperties { Hwnd = drawable.Control.Handle, PixelSize = drawable.ClientSize.ToDx(), PresentOptions = sd.PresentOptions.Immediately }; Control = new sd.WindowRenderTarget(SDFactory.D2D1Factory, renderProp, winProp); } else if (image != null) { var imageHandler = image.Handler as BitmapHandler; renderProp.PixelFormat = new sd.PixelFormat(SharpDX.DXGI.Format.Unknown, sd.AlphaMode.Unknown); Control = new sd.WicRenderTarget(SDFactory.D2D1Factory, imageHandler.Control, renderProp); } }
public InfoText(SharpDX.Direct3D11.Device device, int width, int height) { _immediateContext = device.ImmediateContext; _rect.Size = new Size2F(width, height); _bitmapSize = width * height * 4; IsEnabled = true; using (var factoryWic = new SharpDX.WIC.ImagingFactory()) { _wicBitmap = new SharpDX.WIC.Bitmap(factoryWic, width, height, _pixelFormat, SharpDX.WIC.BitmapCreateCacheOption.CacheOnLoad); } var renderTargetProperties = new RenderTargetProperties(RenderTargetType.Default, new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.R8G8B8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied), 0, 0, RenderTargetUsage.None, SharpDX.Direct2D1.FeatureLevel.Level_DEFAULT); using (var factory2D = new SharpDX.Direct2D1.Factory()) { _wicRenderTarget = new WicRenderTarget(factory2D, _wicBitmap, renderTargetProperties); _wicRenderTarget.TextAntialiasMode = TextAntialiasMode.Default; } using (var factoryDWrite = new SharpDX.DirectWrite.Factory(SharpDX.DirectWrite.FactoryType.Shared)) { _textFormat = new TextFormat(factoryDWrite, "Tahoma", 20); } Color4 color = new Color4(1, 1, 1, 1); _sceneColorBrush = new SolidColorBrush(_wicRenderTarget, color); _clearColor = color; _clearColor.Alpha = 0; _renderTexture = new Texture2D(device, new Texture2DDescription() { ArraySize = 1, BindFlags = BindFlags.ShaderResource, CpuAccessFlags = CpuAccessFlags.Write, Format = Format.R8G8B8A8_UNorm, Height = height, Width = width, MipLevels = 1, OptionFlags = ResourceOptionFlags.None, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Dynamic }); OverlayBufferRes = new ShaderResourceView(device, _renderTexture, new ShaderResourceViewDescription() { Format = _renderTexture.Description.Format, Dimension = ShaderResourceViewDimension.Texture2D, Texture2D = new ShaderResourceViewDescription.Texture2DResource() { MipLevels = 1, MostDetailedMip = 0 } }); }
private void CreateWicTarget() { if (image != null) { var renderProp = CreateRenderProperties(); var imageHandler = image.Handler as BitmapHandler; renderProp.PixelFormat = new sd.PixelFormat(SharpDX.DXGI.Format.Unknown, sd.AlphaMode.Unknown); Control = new sd.WicRenderTarget(SDFactory.D2D1Factory, imageHandler.Control, renderProp); } }
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 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, height-128) }); 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 DUIWICRenderTarget(DUIBitmap image) { System.Threading.Monitor.Enter(lockObj); RenderTargetProperties renderTargetProperties = new RenderTargetProperties { Type = RenderTargetType.Default, DpiX = 96.0f, DpiY = 96.0f, PixelFormat = new PixelFormat(Format.Unknown, SharpDX.Direct2D1.AlphaMode.Unknown), Usage = RenderTargetUsage.None, MinLevel = FeatureLevel.Level_DEFAULT }; this.wicRenderTarget = new SharpDX.Direct2D1.WicRenderTarget(d2dFactory, image, renderTargetProperties); }
public async Task <MemoryStream> RenderToPngStream(FrameworkElement fe) { var width = (int)Math.Ceiling(fe.ActualWidth); var height = (int)Math.Ceiling(fe.ActualHeight); if (width == 0 || height == 0) { throw new InvalidOperationException("Can't render an empty element. ActualWidth or ActualHeight equal 0. Consider awaiting a WaitForNonZeroSizeAsync() call or invoking Measure()/Arrange() before the call to Render()."); } // pixel format with transparency/alpha channel and RGB values premultiplied by alpha var pixelFormat = WIC.PixelFormat.Format32bppPRGBA; using (var wicBitmap = new WIC.Bitmap( this.WicFactory, width, height, pixelFormat, WIC.BitmapCreateCacheOption.CacheOnLoad)) { var renderTargetProperties = new D2D.RenderTargetProperties( D2D.RenderTargetType.Default, new D2D.PixelFormat( Format.R8G8B8A8_UNorm, D2D.AlphaMode.Premultiplied), //new D2DPixelFormat(Format.Unknown, AlphaMode.Unknown), // use this for non-alpha, cleartype antialiased text 0, 0, D2D.RenderTargetUsage.None, D2D.FeatureLevel.Level_DEFAULT); using (var renderTarget = new D2D.WicRenderTarget( this.D2DFactory, wicBitmap, renderTargetProperties) { //TextAntialiasMode = TextAntialiasMode.Cleartype // this only works with the pixel format with no alpha channel TextAntialiasMode = D2D.TextAntialiasMode.Grayscale // this is the best we can do for bitmaps with alpha channels }) { await 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. return(GetBitmapAsStream(wicBitmap)); } }
public RenderTargetBitmapImpl( ImagingFactory imagingFactory, Factory d2dFactory, int width, int height) : base(imagingFactory, width, height) { this.target = new WicRenderTarget( d2dFactory, this.WicImpl, new RenderTargetProperties { DpiX = 96, DpiY = 96, }); }
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 void EncodeImage(this d2.Bitmap target, ImageFormat imageFormat, Stream outputStream) { var width = target.PixelSize.Width; var height = target.PixelSize.Height; var wicBitmap = new wic.Bitmap(DXGraphicsService.FactoryImaging, width, height, wic.PixelFormat.Format32bppBGR, wic.BitmapCreateCacheOption.CacheOnLoad); var renderTargetProperties = new d2.RenderTargetProperties(d2.RenderTargetType.Default, new d2.PixelFormat(Format.Unknown, d2.AlphaMode.Unknown), 0, 0, d2.RenderTargetUsage.None, d2.FeatureLevel.Level_DEFAULT); var d2DRenderTarget = new d2.WicRenderTarget(target.Factory, wicBitmap, renderTargetProperties); d2DRenderTarget.BeginDraw(); d2DRenderTarget.Clear(global::SharpDX.Color.Transparent); d2DRenderTarget.DrawBitmap(target, 1, d2.BitmapInterpolationMode.Linear); d2DRenderTarget.EndDraw(); var stream = new wic.WICStream(DXGraphicsService.FactoryImaging, outputStream); // Initialize a Jpeg encoder with this stream var encoder = new wic.BitmapEncoder(DXGraphicsService.FactoryImaging, GetImageFormat(imageFormat)); encoder.Initialize(stream); // Create a Frame encoder var bitmapFrameEncode = new wic.BitmapFrameEncode(encoder); bitmapFrameEncode.Initialize(); bitmapFrameEncode.SetSize(width, height); Guid pixelFormatGuid = wic.PixelFormat.FormatDontCare; bitmapFrameEncode.SetPixelFormat(ref pixelFormatGuid); bitmapFrameEncode.WriteSource(wicBitmap); bitmapFrameEncode.Commit(); encoder.Commit(); bitmapFrameEncode.Dispose(); encoder.Dispose(); stream.Dispose(); d2DRenderTarget.Dispose(); wicBitmap.Dispose(); }
private void CreateWicTarget() { if (image != null) { var imageHandler = image.Handler as BitmapHandler; if (imageHandler.Control.PixelFormat == PixelFormat.Format24bppRgb.ToWic()) { // image is 24-bit but d2d only supports 32-bit, so make a copy SourceImage = image; image = new Bitmap(image.Width, image.Height, PixelFormat.Format32bppRgba); imageHandler = image.Handler as BitmapHandler; } var renderProp = CreateRenderProperties(); renderProp.PixelFormat = new sd.PixelFormat(SharpDX.DXGI.Format.Unknown, sd.AlphaMode.Unknown); Control = new sd.WicRenderTarget(SDFactory.D2D1Factory, imageHandler.Control, renderProp); } }
public RenderTargetBitmapImpl( ImagingFactory imagingFactory, Factory d2dFactory, int width, int height) : base(imagingFactory, width, height) { var props = new RenderTargetProperties { DpiX = 96, DpiY = 96, }; _target = new WicRenderTarget( d2dFactory, WicImpl, props); }
public Direct2D1RenderTargetBitmap( Factory d2dFactory, ImagingFactory wicFactory, SharpDX.WIC.Bitmap bitmap) : base(wicFactory, bitmap) { double dpiX; double dpiY; this.d2dFactory = d2dFactory; bitmap.GetResolution(out dpiX, out dpiY); this.target = new WicRenderTarget( d2dFactory, bitmap, new RenderTargetProperties { DpiX = (float)dpiX, DpiY = (float)dpiY, }); }
private static void DrawPsd(Person person, WIC.ImagingFactory wic, D2D.Factory d2dFactory, WIC.FormatConverter converter) { using (var wicBitmap = new WIC.Bitmap(wic, (int)ImageDefines.Size, (int)ImageDefines.Size, WIC.PixelFormat.Format32bppPBGRA, WIC.BitmapCreateCacheOption.CacheOnDemand)) using (var target = new D2D.WicRenderTarget(d2dFactory, wicBitmap, new D2D.RenderTargetProperties())) using (var color = new D2D.SolidColorBrush(target, SexColor[person.Sex])) using (var bmp = D2D.Bitmap.FromWicBitmap(target, converter)) using (var bmpBrush = new D2D.BitmapBrush(target, bmp)) { target.BeginDraw(); var offset = (ImageDefines.Size - ImageDefines.RealSize) / 2; bmpBrush.Transform = Matrix3x2.Scaling( ImageDefines.RealSize / bmp.Size.Width, ImageDefines.RealSize / (bmp.Size.Height - 497.0f)) * Matrix3x2.Translation(offset, offset); target.FillEllipse(new D2D.Ellipse( new Vector2(ImageDefines.Size / 2.0f, ImageDefines.Size / 2.0f), ImageDefines.RealSize / 2.0f, ImageDefines.RealSize / 2.0f), bmpBrush); target.DrawEllipse(new D2D.Ellipse( new Vector2(ImageDefines.Size / 2.0f, ImageDefines.Size / 2.0f), ImageDefines.RealSize / 2.0f, ImageDefines.RealSize / 2.0f), color, ImageDefines.LineWidth); target.EndDraw(); using (var file = File.Create(person.PsdImage)) { WicTools.SaveD2DBitmap(wic, wicBitmap, file); } } }
internal D2dWicGraphics(WicRenderTarget renderTarget, SharpDX.WIC.Bitmap wicBitmap) : base(renderTarget) { m_wicBitmap = wicBitmap; }
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 = WIC.PixelFormat.Format32bppPRGBA; // pixel format without transparency, but one that works with Cleartype antialiasing //var pixelFormat = WicPixelFormat.Format32bppBGR; var wicBitmap = new WIC.Bitmap( this.WicFactory, width, height, pixelFormat, WIC.BitmapCreateCacheOption.CacheOnLoad); var renderTargetProperties = new D2D.RenderTargetProperties( D2D.RenderTargetType.Default, new D2D.PixelFormat(Format.R8G8B8A8_UNorm, D2D.AlphaMode.Premultiplied), //new D2DPixelFormat(Format.Unknown, AlphaMode.Unknown), // use this for non-alpha, cleartype antialiased text 0, 0, D2D.RenderTargetUsage.None, D2D.FeatureLevel.Level_DEFAULT); var renderTarget = new D2D.WicRenderTarget( this.D2DFactory, wicBitmap, renderTargetProperties) { //TextAntialiasMode = TextAntialiasMode.Cleartype // this only works with the pixel format with no alpha channel TextAntialiasMode = D2D.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 WIC.WICStream( this.WicFactory, ms); var encoder = new WIC.PngBitmapEncoder(WicFactory); encoder.Initialize(stream); var frameEncoder = new WIC.BitmapFrameEncode(encoder); frameEncoder.Initialize(); frameEncoder.SetSize(width, height); var format = WIC.PixelFormat.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; }
public async Task<MemoryStream> RenderToPngStream(FrameworkElement fe) { var width = (int)Math.Ceiling(fe.ActualWidth); var height = (int)Math.Ceiling(fe.ActualHeight); if (width == 0 || height == 0) { throw new InvalidOperationException("Can't render an empty element. ActualWidth or ActualHeight equal 0. Consider awaiting a WaitForNonZeroSizeAsync() call or invoking Measure()/Arrange() before the call to Render()."); } // pixel format with transparency/alpha channel and RGB values premultiplied by alpha var pixelFormat = WIC.PixelFormat.Format32bppPRGBA; using (var wicBitmap = new WIC.Bitmap( this.WicFactory, width, height, pixelFormat, WIC.BitmapCreateCacheOption.CacheOnLoad)) { var renderTargetProperties = new D2D.RenderTargetProperties( D2D.RenderTargetType.Default, new D2D.PixelFormat( Format.R8G8B8A8_UNorm, D2D.AlphaMode.Premultiplied), //new D2DPixelFormat(Format.Unknown, AlphaMode.Unknown), // use this for non-alpha, cleartype antialiased text 0, 0, D2D.RenderTargetUsage.None, D2D.FeatureLevel.Level_DEFAULT); using (var renderTarget = new D2D.WicRenderTarget( this.D2DFactory, wicBitmap, renderTargetProperties) { //TextAntialiasMode = TextAntialiasMode.Cleartype // this only works with the pixel format with no alpha channel TextAntialiasMode = D2D.TextAntialiasMode.Grayscale // this is the best we can do for bitmaps with alpha channels }) { await 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. return GetBitmapAsStream(wicBitmap); } }
protected void ReleaseResources() { _bitmap.Dispose(); _bitmap = null; _renderTarget.Dispose(); _renderTarget = null; }
private void CreateBitmap(int width, int height) { if (_bitmap == null || (_bitmap.Size.Width < width || _bitmap.Size.Height < height)) { //RenderTargetProperties rtp = new RenderTargetProperties(RenderTargetType.Default, // new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.R8G8B8A8_UNorm, AlphaMode.Premultiplied), // Factory2D.DesktopDpi.Width, // Factory2D.DesktopDpi.Height, // RenderTargetUsage.None, // FeatureLevel.Level_DEFAULT); try { var pixelFormat = SharpDX.WIC.PixelFormat.Format32bppPRGBA; _bitmap = new SharpDX.WIC.Bitmap(FactoryImaging, width, height, pixelFormat, BitmapCreateCacheOption.CacheOnLoad); _renderTarget = new WicRenderTarget(Factory2D, _bitmap, new RenderTargetProperties()); //_renderTarget = new WicRenderTarget(Factory2D, _bitmap, rtpGDI); if (_brush == null) { _brush = new SolidColorBrush(_renderTarget, new Color4(new Color3(1, 1, 1), 1.0f)); } } catch (Exception exc) { var ss = exc.Message; } } }
// // 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 void Dispose() { if (_renderTexture != null) { _renderTexture.Dispose(); _renderTexture = null; } if (_wicBitmap != null) { _wicBitmap.Dispose(); _wicBitmap = null; } if (_wicRenderTarget != null) { _wicRenderTarget.Dispose(); _wicRenderTarget = null; } if (_sceneColorBrush != null) { _sceneColorBrush.Dispose(); _sceneColorBrush = null; } if (OverlayBufferRes != null) { OverlayBufferRes.Dispose(); OverlayBufferRes = null; } if (_textFormat != null) { _textFormat.Dispose(); _textFormat = null; } }
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 = WIC.PixelFormat.Format32bppPRGBA; // pixel format without transparency, but one that works with Cleartype antialiasing //var pixelFormat = WicPixelFormat.Format32bppBGR; var wicBitmap = new WIC.Bitmap( this.WicFactory, width, height, pixelFormat, WIC.BitmapCreateCacheOption.CacheOnLoad); var renderTargetProperties = new D2D.RenderTargetProperties( D2D.RenderTargetType.Default, new D2D.PixelFormat(Format.R8G8B8A8_UNorm, D2D.AlphaMode.Premultiplied), //new D2DPixelFormat(Format.Unknown, AlphaMode.Unknown), // use this for non-alpha, cleartype antialiased text 0, 0, D2D.RenderTargetUsage.None, D2D.FeatureLevel.Level_DEFAULT); var renderTarget = new D2D.WicRenderTarget( this.D2DFactory, wicBitmap, renderTargetProperties) { //TextAntialiasMode = TextAntialiasMode.Cleartype // this only works with the pixel format with no alpha channel TextAntialiasMode = D2D.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 WIC.WICStream( this.WicFactory, ms); var encoder = new WIC.PngBitmapEncoder(WicFactory); encoder.Initialize(stream); var frameEncoder = new WIC.BitmapFrameEncode(encoder); frameEncoder.Initialize(); frameEncoder.SetSize(width, height); var format = WIC.PixelFormat.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); }
/// <summary> /// 制作背景图片 /// </summary> /// <param name="pictureFileFullPath"></param> /// <param name="fileDirectory"></param> /// <param name="textContent"></param> /// <returns></returns> static string GenerateWallPaper(string pictureFileFullPath, string fileDirectory, string textContent) { var wic = new SharpDX.WIC.ImagingFactory2(); var d2d = new SharpDX.Direct2D1.Factory(); float dpi = d2d.DesktopDpi.Width; Size2 size = new Size2(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height); SharpDX.WIC.FormatConverter image = CreateWicImage(wic, pictureFileFullPath); using var wicBitmap = new SharpDX.WIC.Bitmap(wic, size.Width, size.Height, SharpDX.WIC.PixelFormat.Format32bppPBGRA, SharpDX.WIC.BitmapCreateCacheOption.CacheOnDemand); using var target = new SharpDX.Direct2D1.WicRenderTarget(d2d, wicBitmap, new SharpDX.Direct2D1.RenderTargetProperties()); using var dc = target.QueryInterface <SharpDX.Direct2D1.DeviceContext>(); using var bmpPicture = SharpDX.Direct2D1.Bitmap.FromWicBitmap(target, image); using var dwriteFactory = new SharpDX.DirectWrite.Factory(); using var brush = new SolidColorBrush(target, SharpDX.Color.LightGoldenrodYellow); using var bmpLayer = new SharpDX.Direct2D1.Bitmap1(dc, target.PixelSize, new SharpDX.Direct2D1.BitmapProperties1(new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied), dpi, dpi, SharpDX.Direct2D1.BitmapOptions.Target)); var oldTarget = dc.Target; dc.Target = bmpLayer; target.BeginDraw(); { var textFormat = new SharpDX.DirectWrite.TextFormat(dwriteFactory, "Tahoma", size.Height / 27); // draw textContent { var textLayout = new SharpDX.DirectWrite.TextLayout(dwriteFactory, textContent, textFormat, target.Size.Width * 0.75f, float.MaxValue); var center = new Vector2((target.Size.Width - textLayout.Metrics.Width) / 2, (target.Size.Height - textLayout.Metrics.Height) / 2); target.DrawTextLayout(new Vector2(center.X, center.Y), textLayout, brush); } //{ // // draw otherContent // var textLayout = new SharpDX.DirectWrite.TextLayout(dwriteFactory, chinese, textFormat, target.Size.Width * 0.75f, float.MaxValue); // var center = new Vector2((target.Size.Width - textLayout.Metrics.Width) / 2, target.Size.Height - textLayout.Metrics.Height - size.Height / 18); // target.DrawTextLayout(new Vector2(center.X, center.Y), textLayout, brush); //} } target.EndDraw(); // shadow var shadow = new SharpDX.Direct2D1.Effects.Shadow(dc); shadow.SetInput(0, bmpLayer, new RawBool(false)); dc.Target = oldTarget; target.BeginDraw(); { target.DrawBitmap(bmpPicture, new SharpDX.RectangleF(0, 0, target.Size.Width, target.Size.Height), 1.0f, BitmapInterpolationMode.Linear); dc.DrawImage(shadow, new Vector2(size.Height / 150.0f, size.Height / 150.0f)); dc.UnitMode = UnitMode.Pixels; target.DrawBitmap(bmpLayer, 1.0f, BitmapInterpolationMode.Linear); } target.EndDraw(); if (!Directory.Exists(fileDirectory)) { Directory.CreateDirectory(fileDirectory); } string wallpaperFileName = fileDirectory + DateTime.Now.ToString("yyyyMMdd") + "_" + "wallpaper.png"; using var wallpaperStream = File.OpenWrite(wallpaperFileName); SaveD2DBitmap(wic, wicBitmap, wallpaperStream); wallpaperStream.Close(); return(wallpaperFileName); }
public static string GenerateWallpaper(string pictureFileName, string english, string chinese, string weather) { var wic = new WIC.ImagingFactory2(); var d2d = new D2D.Factory(); float dpi = d2d.DesktopDpi.Width; Size2 size = new Size2(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height); WIC.FormatConverter image = CreateWicImage(wic, pictureFileName); using (var wicBitmap = new WIC.Bitmap(wic, size.Width, size.Height, WIC.PixelFormat.Format32bppPBGRA, WIC.BitmapCreateCacheOption.CacheOnDemand)) using (var target = new D2D.WicRenderTarget(d2d, wicBitmap, new D2D.RenderTargetProperties())) using (var dc = target.QueryInterface <D2D.DeviceContext>()) using (var bmpPicture = Bitmap.FromWicBitmap(target, image)) using (var dwriteFactory = new SharpDX.DirectWrite.Factory()) using (var brush = new SolidColorBrush(target, new RawColor4(255, 255, 0, 1))) using (var bmpLayer = new D2D.Bitmap1(dc, target.PixelSize, new D2D.BitmapProperties1(new D2D.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, AlphaMode.Premultiplied), dpi, dpi, BitmapOptions.Target))) { var oldTarget = dc.Target; dc.Target = bmpLayer; target.BeginDraw(); { var textFormat = new DWrite.TextFormat(dwriteFactory, "Tahoma", size.Height / 27); // draw English { var textLayout = new DWrite.TextLayout(dwriteFactory, english, textFormat, target.Size.Width * 0.75f, float.MaxValue); var center = new Vector2((target.Size.Width - textLayout.Metrics.Width) / 2, (target.Size.Height - textLayout.Metrics.Height) / 2); target.DrawTextLayout(new RawVector2(center.X, center.Y), textLayout, brush); } { var textLayout = new DWrite.TextLayout(dwriteFactory, chinese, textFormat, target.Size.Width * 0.75f, float.MaxValue); var center = new Vector2((target.Size.Width - textLayout.Metrics.Width) / 2, target.Size.Height - textLayout.Metrics.Height - size.Height / 18); target.DrawTextLayout(new RawVector2(center.X, center.Y), textLayout, brush); } { var textLayout = new DWrite.TextLayout(dwriteFactory, weather, textFormat, target.Size.Width * 0.75f, float.MaxValue); var center = new Vector2((target.Size.Width - textLayout.Metrics.Width) / 2, size.Height / 18 + textLayout.Metrics.Height); target.DrawTextLayout(new RawVector2(center.X, center.Y), textLayout, brush); } } target.EndDraw(); // shadow var shadow = new D2D.Effects.Shadow(dc); shadow.SetInput(0, bmpLayer, new RawBool(false)); dc.Target = oldTarget; target.BeginDraw(); { target.DrawBitmap(bmpPicture, new SharpDX.Mathematics.Interop.RawRectangleF(0, 0, target.Size.Width, target.Size.Height), 1.0f, BitmapInterpolationMode.Linear); dc.DrawImage(shadow, new RawVector2(size.Height / 150.0f, size.Height / 150.0f)); dc.UnitMode = UnitMode.Pixels; target.DrawBitmap(bmpLayer, 1.0f, BitmapInterpolationMode.Linear); } target.EndDraw(); string wallpaperFileName = Path.GetTempPath() + "wallpaper.png"; using (var wallpaperStream = File.OpenWrite(wallpaperFileName)) { SaveD2DBitmap(wic, wicBitmap, wallpaperStream); wallpaperStream.Close(); return(wallpaperFileName); } } }
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 *= contentScaleFactorWidth; textDef.Dimensions.Width *= contentScaleFactorWidth; textDef.Dimensions.Height *= contentScaleFactorHeight; var font = CreateFont(textDef.FontName, textDef.FontSize); if (font == null) { CCLog.Log("Can not create font {0} with size {1}.", textDef.FontName, textDef.FontSize); return new CCTexture2D(); } var _currentFontSizeEm = textDef.FontSize; var _currentDIP = ConvertPointSizeToDIP(_currentFontSizeEm); // color var foregroundColor = Color4.White; // 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 static byte[] CreatePngImage(int width, int height, string text, float fontSize = 30.0f, string font = "Times New Roman", int lineCount = 5, bool rotation = false, float turbulenceAmount = 60.0f) { using (var wic = new WIC.ImagingFactory2()) using (var d2d = new D2D.Factory()) using (var wicBitmap = new WIC.Bitmap(wic, width, height, WIC.PixelFormat.Format32bppPBGRA, WIC.BitmapCreateCacheOption.CacheOnDemand)) using (var target = new D2D.WicRenderTarget(d2d, wicBitmap, new D2D.RenderTargetProperties())) using (var dwriteFactory = new DWrite.Factory()) using (var brush = new D2D.SolidColorBrush(target, Color.Yellow)) using (var encoder = new WIC.PngBitmapEncoder(wic)) using (var ms = new MemoryStream()) using (var dc = target.QueryInterface <D2D.DeviceContext>()) using (var bmpLayer = new D2D.Bitmap1(dc, target.PixelSize, new D2D.BitmapProperties1(new D2D.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, D2D.AlphaMode.Premultiplied), d2d.DesktopDpi.Width, d2d.DesktopDpi.Height, D2D.BitmapOptions.Target))) { var r = new Random(); encoder.Initialize(ms); D2D.Image oldTarget = dc.Target; { dc.Target = bmpLayer; dc.BeginDraw(); var textFormat = new DWrite.TextFormat(dwriteFactory, font, fontSize); for (int charIndex = 0; charIndex < text.Length; ++charIndex) { using (var layout = new DWrite.TextLayout(dwriteFactory, text[charIndex].ToString(), textFormat, float.MaxValue, float.MaxValue)) { var layoutSize = new Vector2(layout.Metrics.Width, layout.Metrics.Height); using (var b2 = new D2D.LinearGradientBrush(dc, new D2D.LinearGradientBrushProperties { StartPoint = Vector2.Zero, EndPoint = layoutSize, }, new D2D.GradientStopCollection(dc, new[] { new D2D.GradientStop { Position = 0.0f, Color = ColorFromHsl(r.NextFloat(0, 1), 1.0f, 0.8f) }, new D2D.GradientStop { Position = 1.0f, Color = ColorFromHsl(r.NextFloat(0, 1), 1.0f, 0.8f) }, }))) { var position = new Vector2(charIndex * width / text.Length, r.NextFloat(0, height - layout.Metrics.Height)); dc.Transform = Matrix3x2.Translation(-layoutSize / 2) * Matrix3x2.Skew(r.NextFloat(0, 0.5f), r.NextFloat(0, 0.5f)) * (rotation ? Matrix3x2.Rotation(r.NextFloat(0, (float)(Math.PI * 2))) : Matrix3x2.Identity) * Matrix3x2.Translation(position + layoutSize / 2); dc.DrawTextLayout(Vector2.Zero, layout, b2); } } } for (var i = 0; i < lineCount; ++i) { target.Transform = Matrix3x2.Identity; brush.Color = ColorFromHsl(r.NextFloat(0, 1), 1.0f, 0.3f); target.DrawLine( r.NextVector2(Vector2.Zero, new Vector2(width, height)), r.NextVector2(Vector2.Zero, new Vector2(width, height)), brush, 3.0f); } target.EndDraw(); } Color background = ColorFromHsl(r.NextFloat(0, 1), 1.0f, 0.3f); { dc.Target = null; using (var displacement = new D2D.Effects.DisplacementMap(dc)) { displacement.SetInput(0, bmpLayer, true); displacement.Scale = turbulenceAmount; var turbulence = new D2D.Effects.Turbulence(dc); displacement.SetInputEffect(1, turbulence); dc.Target = oldTarget; dc.BeginDraw(); dc.Clear(background); dc.DrawImage(displacement); dc.EndDraw(); using (var frame = new WIC.BitmapFrameEncode(encoder)) { frame.Initialize(); frame.SetSize(wicBitmap.Size.Width, wicBitmap.Size.Height); var pixelFormat = wicBitmap.PixelFormat; frame.SetPixelFormat(ref pixelFormat); frame.WriteSource(wicBitmap); frame.Commit(); } } } encoder.Commit(); return(ms.ToArray()); } }