/// <summary> /// Создает карту битов из массива битов /// </summary> /// <param name="data">Массив битов который будет записан в карту</param> /// <param name="rt">Рендер таргет связанный с текущей видеокартой можно получить из класса TextWriter</param> /// <param name="Width">Ширина Будущей картинки в писелях</param> /// <param name="Height">Высота карты битов в пикселях</param> /// <returns></returns> public static SharpDX.Direct2D1.Bitmap BimapFromByteArray(byte[] data, RenderTarget rt, int Width, int Height) { var _backBufferBmp = new SharpDX.Direct2D1.Bitmap(rt, new Size2(Width, Height), new BitmapProperties(rt.PixelFormat)); _backBufferBmp.CopyFromMemory(data, Width * 4); return(_backBufferBmp); }
public override void Measure() //todo: Will lead to NullReferenceException when recreated window on some maps: s/552702 { if (!_isStart && _status != OsuModel.Status) { _isStart = true; } if (!_isStart) { return; } if (_currentMapPath != OsuModel.Idle.NowMap.Folder) { _currentMapPath = OsuModel.Idle.NowMap.Folder; var currentBgPath = Path.Combine(_currentMapPath, OsuModel.Idle.NowMap.BackgroundFilename); if (File.Exists(currentBgPath)) { _oldBg = _newBg; _newBg = RenderTarget.LoadBitmap(currentBgPath); _lastBgIsNull = false; } else if (_defaultBg != null) { if (_lastBgIsNull) { return; } _oldBg = _newBg; _newBg = _defaultBg; _lastBgIsNull = true; } else { return; } _fixedRectOld = _fixedRect; _fixedRect = GetBgPosition(_newBg.Size); var size = Settings.Render.WindowSize; if (_newBg != null) { _newBgObj = new BitmapObject(RenderTarget, _newBg, Origin.Default, new Mathe.RawPoint(size.Width / 2, size.Height / 2)); } if (_oldBg != null) { _oldBgObj = new BitmapObject(RenderTarget, _oldBg, Origin.Default, new Mathe.RawPoint(size.Width / 2, size.Height / 2)); } _transformStyle = _rnd.Next(0, 3); if (sw.ElapsedMilliseconds < 600 && sw.ElapsedMilliseconds != 0) { _transformStyle = 99; } sw.Restart(); } }
/// <summary> /// Initializes a new DirectXTexture class. /// </summary> /// <param name="bmp">The Bitmap.</param> internal DirectXTexture(System.Drawing.Bitmap bmp) { RawBitmap = (System.Drawing.Bitmap)bmp.Clone(); _width = bmp.Width; _height = bmp.Height; var sourceArea = new Rectangle(0, 0, bmp.Width, bmp.Height); var bitmapProperties = new BitmapProperties( new PixelFormat(Format.R8G8B8A8_UNorm, AlphaMode.Premultiplied), 96, 96); var size = new Size2(bmp.Width, bmp.Height); int stride = bmp.Width * sizeof(int); using (var tempStream = new DataStream(bmp.Height * stride, true, true)) { BitmapData bitmapData = bmp.LockBits(sourceArea, ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppPArgb); for (int y = 0; y < bmp.Height; y++) { int offset = bitmapData.Stride * y; for (int x = 0; x < bmp.Width; x++) { byte b = Marshal.ReadByte(bitmapData.Scan0, offset++); byte g = Marshal.ReadByte(bitmapData.Scan0, offset++); byte r = Marshal.ReadByte(bitmapData.Scan0, offset++); byte a = Marshal.ReadByte(bitmapData.Scan0, offset++); int rgba = r | (g << 8) | (b << 16) | (a << 24); tempStream.Write(rgba); } } bmp.UnlockBits(bitmapData); tempStream.Position = 0; _bmp = new Bitmap(DirectXHelper.RenderTarget, size, tempStream, stride, bitmapProperties); } }
public image_sol(string filename, SharpDX.Direct2D1.RenderTarget d2d_render_target) { path = filename; System.Security.Cryptography.RandomNumberGenerator rng = System.Security.Cryptography.RandomNumberGenerator.Create(); byte[] arr = new byte[16]; rng.GetNonZeroBytes(arr); rand = new Random(BitConverter.ToInt32(arr, 0)); rng.Dispose(); points_count = 0; try { using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { BitmapFrame bmpFrame = BitmapFrame.Create(fs); width = bmpFrame.PixelWidth; height = bmpFrame.PixelHeight; } } catch { width = 200; height = 100; path = "invalid"; } bitmap = LoadFromFile(d2d_render_target, path); ipts = new List <IPoint>(); }
public void DrawImage(Bitmap bitmap, float x, float y, float w, float h, float sx, float sy, float sw, float sh, float opacity) { var dest = new RawRectangleF(x, y, x + w, y + h); var src = new RawRectangleF(sx, sy, sx + sw, sy + sh); RenderTarget.DrawBitmap(bitmap, dest, opacity, BitmapInterpolationMode.Linear, src); }
public void DrawImage(Bitmap bitmap, float x, float y, float opacity) { var size = bitmap.Size; var dest = new RawRectangleF(x, y, size.Width, size.Height); RenderTarget.DrawBitmap(bitmap, dest, opacity, BitmapInterpolationMode.Linear); }
public static void ToBitmap(SharpDXInfo info) { var m_texture = Texture2D.FromSwapChain <Texture2D>(info.SwapChain, 0); var m_surface = m_texture.QueryInterface <Surface>(); D2D.RenderTarget m_renderTarget; using (D2D.Factory factory = new D2D.Factory()) { m_renderTarget = new D2D.RenderTarget( factory, m_surface, new D2D.RenderTargetProperties() { DpiX = 0.0f, // default dpi DpiY = 0.0f, // default dpi MinLevel = D2D.FeatureLevel.Level_DEFAULT, Type = D2D.RenderTargetType.Hardware, Usage = D2D.RenderTargetUsage.None, PixelFormat = new D2D.PixelFormat( Format.Unknown, D2D.AlphaMode.Premultiplied ) } ); } var m_bitmap = new D2D.Bitmap(m_renderTarget, m_surface); }
public static SharpDX.Direct2D1.Bitmap LoadBitmapFromResourceName(this RenderTarget renderTarget, string resourceName) { System.Drawing.Bitmap bitmap2; System.Drawing.Bitmap image = new System.Drawing.Bitmap(typeof(MusicCanvasControl), resourceName); if (image.PixelFormat != System.Drawing.Imaging.PixelFormat.Format32bppPArgb) { bitmap2 = new System.Drawing.Bitmap(image.Width, image.Height, System.Drawing.Imaging.PixelFormat.Format32bppPArgb); using (Graphics graphics = Graphics.FromImage(bitmap2)) { graphics.DrawImage(image, 0, 0, image.Width, image.Height); } } else { bitmap2 = image; } BitmapData bitmapdata = bitmap2.LockBits(new Rectangle(0, 0, bitmap2.Width, bitmap2.Height), ImageLockMode.ReadOnly, bitmap2.PixelFormat); int length = bitmapdata.Stride * bitmap2.Height; byte[] destination = new byte[length]; Marshal.Copy(bitmapdata.Scan0, destination, 0, length); bitmap2.UnlockBits(bitmapdata); SharpDX.Direct2D1.PixelFormat pixelFormat = new SharpDX.Direct2D1.PixelFormat(Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied); BitmapProperties bitmapProperties = new BitmapProperties(pixelFormat, bitmap2.HorizontalResolution, bitmap2.VerticalResolution); SharpDX.Direct2D1.Bitmap bitmap3 = new SharpDX.Direct2D1.Bitmap(renderTarget, new Size2(bitmap2.Width, bitmap2.Height), bitmapProperties); bitmap3.CopyFromMemory(destination, bitmapdata.Stride); bitmap2.Dispose(); image.Dispose(); return(bitmap3); }
void DrawToWindow() { while (_queue.Count != 0) { if (_queue.TryTake(out SharpDX.Direct2D1.Bitmap bitmap) == true) { if (_lastBitmap != null) { _lastBitmap.Dispose(); } _lastBitmap = bitmap; } if (_lastBitmap == null) { return; } _renderTarget.Render( (renderer) => { renderer.DrawBitmap(_lastBitmap, 1.0f, BitmapInterpolationMode.Linear); }); Captured?.Invoke(this, new CapturedEventArgs(_lastBitmap, _dataStream)); } }
} // RotateImage() public void Resize(Size newSize) { this.imageGDI = new System.Drawing.Bitmap(this.imageGDI, newSize); this.imageDirect2D = GetDirect2DBitmapWithSharpDX(MyDevice2D.render[this.idRender], this.imageGDI); this.size = new SizeF(newSize.Width, newSize.Height); } // Resize()
public Camera() { renderForm = new RenderForm("VirtualCamera"); renderForm.ClientSize = new Size(Width, Height); renderForm.AllowUserResizing = false; Position = new Vector3(0, 0, 0); Target = new Vector3(0, 0, 9f); SceneCache = new byte[Width * Height * 4]; RenderTargetProperties renderTargetProperties = new RenderTargetProperties() { Type = SharpDX.Direct2D1.RenderTargetType.Hardware, PixelFormat = new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.R8G8B8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Ignore), DpiX = 0, DpiY = 0, Usage = SharpDX.Direct2D1.RenderTargetUsage.None, MinLevel = SharpDX.Direct2D1.FeatureLevel.Level_10 }; var hwndProperties = new SharpDX.Direct2D1.HwndRenderTargetProperties() { Hwnd = renderForm.Handle, PixelSize = new SharpDX.Size2(Width, Height), PresentOptions = SharpDX.Direct2D1.PresentOptions.Immediately }; CameraView = new WindowRenderTarget(new Factory(), renderTargetProperties, hwndProperties); SceneBuffer = new SharpDX.Direct2D1.Bitmap(CameraView, new SharpDX.Size2(Width, Height), new SharpDX.Direct2D1.BitmapProperties(CameraView.PixelFormat)); SceneObjects = new List <Sphere>(); Light = new LightSource(0, 10, 20); }
public void OnClicked(MouseEventArgs e, Mathe.RawRectangleF recF) { if (!_isBoxing) { _selectedRec = recF; if (!_boardMap.Keys.Contains(recF)) { return; } int i = _boardMap[recF]; Debug.WriteLine(i); ShowBox(e, recF, i); } else { Rectangles = _tmpRectangles.ToArray().ToList(); _tmpRectangles.Clear(); _boxBitmap = null; _boxRec = default; _isBoxing = false; } }
/// <summary> /// 换帧特效 /// </summary> private void DoEffect() { while (_running) { double elapsedTime = DateTime.Now.Subtract(_startDate).TotalMilliseconds; if (elapsedTime >= _effectTime) { DrawPicture(_lstAD[_nextIndex], 0, 0, null, 0, 0); _currentIndex = _nextIndex; return; } DateTime dtBegin = DateTime.Now; SharpDX.Direct2D1.Bitmap curImage = _lstAD[_currentIndex]; SharpDX.Direct2D1.Bitmap nextImage = _lstAD[_nextIndex]; double curX = -((double)_imageSize.Width * elapsedTime / _effectTime); double nextX = (double)_imageSize.Width + curX; //DrawPicture(curImage, curX, 0f, null, nextX, 0f); DrawPicture(curImage, Convert.ToSingle(curX), 0f, nextImage, Convert.ToSingle(nextX), 0f); DateTime dtEnd = DateTime.Now; int sleepTime = (int)(_fpsMilliseconds - dtEnd.Subtract(dtBegin).TotalMilliseconds); if (sleepTime > 0) { Thread.Sleep(sleepTime); } } }
public static SharpDX.Direct2D1.Bitmap Test(SharpDX.Direct2D1.DeviceContext dc, ImagingFactory factory, System.Windows.Media.Imaging.BitmapSource src) { // PixelFormat settings/conversion if (src.Format != System.Windows.Media.PixelFormats.Bgra32) { // Convert BitmapSource FormatConvertedBitmap fcb = new FormatConvertedBitmap(); fcb.BeginInit(); fcb.Source = src; fcb.DestinationFormat = PixelFormats.Bgra32; fcb.EndInit(); src = fcb; } SharpDX.Direct2D1.Bitmap retval = null; try { int stride = src.PixelWidth * (src.Format.BitsPerPixel + 7) / 8; int bufferSize = stride * src.PixelHeight; byte[] buffer = new byte[bufferSize]; src.CopyPixels(Int32Rect.Empty, buffer, stride, 0); GCHandle pinnedArray = GCHandle.Alloc(buffer, GCHandleType.Pinned); IntPtr pointer = pinnedArray.AddrOfPinnedObject(); SharpDX.DataStream datastream = new SharpDX.DataStream(pointer, bufferSize, true, true); var bmpProps1 = new SharpDX.Direct2D1.BitmapProperties1(dc.PixelFormat, dc.Factory.DesktopDpi.Width, dc.Factory.DesktopDpi.Height); retval = new SharpDX.Direct2D1.Bitmap1(dc, new SharpDX.Size2(src.PixelWidth, src.PixelHeight), datastream, stride, bmpProps1); pinnedArray.Free(); } catch (Exception e) { } return(retval); }
public BgDxLayer(D2D.RenderTarget renderTarget, DxLoadObject settings, OsuModel osuModel) : base(renderTarget, settings, osuModel) { _status = OsuModel.Status; string defName = "default.png"; string covName = "cover.png"; var defBgPath = Path.Combine(OsuLivePlayerPlugin.GeneralConfig.WorkPath, defName); var covBgPath = Path.Combine(OsuLivePlayerPlugin.GeneralConfig.WorkPath, covName); if (File.Exists(defBgPath)) { _defaultBg = renderTarget.LoadBitmap(defBgPath); } else { LogUtil.LogError($"Can not find \"{defName}\""); } if (File.Exists(covBgPath)) { _coverBg = renderTarget.LoadBitmap(covBgPath); } else { LogUtil.LogError($"Can not find \"{covName}\""); } var size = Settings.Render.WindowSize; _windowRect = new Mathe.RawRectangleF(0, 0, size.Width, size.Height); }
public StoryboardObject(Element element, Timing timing, D2D.RenderTarget target, Size2F vSize) { _timing = timing; _element = element; _vSize = vSize; var path = Path.Combine(App.StoryboardProvider.Directory, element.ImagePath); if (!File.Exists(path)) { var pngPath = path + ".png"; if (File.Exists(pngPath)) { path = pngPath; } else { path = path + ".jpg"; } } if (File.Exists(path)) { TextureList = new[] { TextureLoader.LoadBitmap(target, path) }; Texture = TextureList[0]; } else { return; } SetDefaultValue(); SetMinMax(); }
private void CaptureLoop(DXGIManager manager, System.Windows.Forms.Control controlToDraw) { _dataStream = new DataStream(_clipRect.Width * _clipRect.Height * 4, true, true); while (true) { int signalId = EventWaitHandle.WaitAny(_waitSignals, Timeout.Infinite); if (signalId == 0) { break; } if (manager.Capture(copyFrameBuffer, 1000) == true) { SharpDX.Direct2D1.Bitmap bitmap = _renderTarget.CreateBitmap(_dataStream); if (bitmap != null) { _queue.Add(bitmap); } } if (controlToDraw.Created) { controlToDraw.BeginInvoke((Action)(() => this.DrawToWindow())); } } }
static void SHDXOverlay_BeforeDrawingEvent(object sender, ExternalUtilsCSharp.UI.Overlay <SharpDXRenderer, SharpDX.Color, SharpDX.Vector2, TextFormat> .OverlayEventArgs e) { if (ranksBmp == null) { System.Drawing.Bitmap bmp = (System.Drawing.Bitmap)Resources.ResourceManager.GetObject("uc_exclusive"); try { ranksBmp = SDXBitmapFromSysBitmap(e.Overlay.Renderer.Device, bmp); } catch { } } else { SharpDX.RectangleF source = new SharpDX.RectangleF(0, 0, ranksBmp.PixelSize.Width, ranksBmp.PixelSize.Height); float mul = 1f + 0.2f * (float)Math.Sin(DateTime.Now.TimeOfDay.TotalSeconds * 0.5f); SharpDX.RectangleF dest = new SharpDX.RectangleF(e.Overlay.Width / 2f - source.Width / 2f * mul, e.Overlay.Height - source.Height * 2f * mul, source.Width * mul, source.Height * mul); e.Overlay.Renderer.Device.DrawBitmap(ranksBmp, dest, 0.9f, BitmapInterpolationMode.Linear, source); } if (ConfigUtils.GetValue <bool>("aimEnabled") && ConfigUtils.GetValue <bool>("aimDrawFov")) { float fov = ConfigUtils.GetValue <float>("aimFov"); SharpDX.Color foreColor = new SharpDX.Color(0.2f, 0.2f, 0.2f, 0.8f); SharpDX.Color backColor = new SharpDX.Color(0.8f, 0.8f, 0.8f, 0.9f); SharpDX.Vector2 size = new SharpDX.Vector2(e.Overlay.Width / 90f * fov); SharpDX.Vector2 center = new SharpDX.Vector2(e.Overlay.Width / 2f, e.Overlay.Height / 2f); e.Overlay.Renderer.DrawEllipse(foreColor, center, size, true, 3f); e.Overlay.Renderer.DrawEllipse(backColor, center, size, true); } }
public override void Init() { // create Direct2D1 Factory factory = new Factory(); //Set Rendering properties RenderTargetProperties renderProp = new RenderTargetProperties() { PixelFormat = new PixelFormat(SharpDX.DXGI.Format.R8G8B8A8_UNorm, AlphaMode.Premultiplied), }; //set hwnd target properties (permit to attach Direct2D to window) HwndRenderTargetProperties winProp = new HwndRenderTargetProperties() { Hwnd = UIForm.Handle, PixelSize = new Size2(Width, Height), PresentOptions = PresentOptions.None }; //target creation DrawTarget = new WindowRenderTarget(factory, renderProp, winProp); // create Bitmap BitmapBuffer = new SharpDX.Direct2D1.Bitmap(DrawTarget, new Size2(Width, Height), new BitmapProperties(DrawTarget.PixelFormat)); //Start to draw DrawTarget.BeginDraw(); DrawTarget.Clear(new SharpDX.Mathematics.Interop.RawColor4(0f, 0f, 0f, 1f)); DrawTarget.EndDraw(); // init events UIForm.KeyDown += new KeyEventHandler(EventsKeyboardDown); UIForm.KeyUp += new KeyEventHandler(EventsKeyboardUp); UIForm.FormClosed += new FormClosedEventHandler(EventsQuit); }
private void CreateAndAddNinePartsBitmap(string bitmapName) { DecodedNinePartsBitmap decoded = _decodedNinePartsBitmaps[bitmapName]; Direct2DBitmap bitmap = CreateBitmap(decoded.Bitmap); _ninePartsBitmaps.Add(bitmapName, new NinePartsBitmap(_renderTarget, bitmap, decoded.Left, decoded.Right, decoded.Top, decoded.Bottom)); }
protected override void OnLoad(EventArgs e) { base.OnLoad(e); // Direct2D var renderTargetProperties = new RenderTargetProperties() { PixelFormat = new PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, AlphaMode.Ignore) }; var hwndRenderTargetProperties = new HwndRenderTargetProperties() { Hwnd = this.Handle, PixelSize = new Size2(bounds.Width, bounds.Height), PresentOptions = PresentOptions.Immediately, }; renderTarget = new WindowRenderTarget(factory, renderTargetProperties, hwndRenderTargetProperties); var bitmapProperties = new BitmapProperties() { PixelFormat = new PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, AlphaMode.Ignore) }; bitmap = new SharpDX.Direct2D1.Bitmap(renderTarget, new Size2(bounds.Width, bounds.Height), bitmapProperties); textFormat = new TextFormat(directWriteFacrtory, "Arial", FontWeight.Normal, SharpDX.DirectWrite.FontStyle.Normal, 96.0f); textFormat.ParagraphAlignment = ParagraphAlignment.Center; textFormat.TextAlignment = TextAlignment.Center; solidColorBrush = new SolidColorBrush(renderTarget, Color4.White); }
private void InitializeSharpDx() { this.Factory = new SharpDX.Direct2D1.Factory(); this.FontFactory = new SharpDX.DirectWrite.Factory(); var renderProp = new SharpDX.Direct2D1.HwndRenderTargetProperties() { Hwnd = this.Handle, PixelSize = new SharpDX.Size2(this.Width, this.Height), PresentOptions = SharpDX.Direct2D1.PresentOptions.None }; this.Device = new SharpDX.Direct2D1.WindowRenderTarget( this.Factory, new SharpDX.Direct2D1.RenderTargetProperties( new SharpDX.Direct2D1.PixelFormat( SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied) ), renderProp); this.Device.TextAntialiasMode = SharpDX.Direct2D1.TextAntialiasMode.Cleartype; this.TimeTextFormat = new SharpDX.DirectWrite.TextFormat(this.FontFactory, "Arial", SharpDX.DirectWrite.FontWeight.DemiBold, SharpDX.DirectWrite.FontStyle.Normal, 21.35f); this.TimeBrush = new SharpDX.Direct2D1.SolidColorBrush(this.Device, new SharpDX.Color4(168 / 255.0f, 58 / 255.0f, 58 / 255.0f, 1.0f)); this.DutyEntryBackgroundImage = ConvertBitmap(this.Device, dutynotifier.Properties.Resources.background); }
} // Resize() internal static Bitmap GetDirect2DBitmapWithSharpDX(RenderTarget rt, System.Drawing.Bitmap image) { if (image == null) { throw new ArgumentNullException("image"); } if (image.PixelFormat != GdiPixelFormat.Format32bppArgb) { return(null); } var imageData = image.LockBits(new System.Drawing.Rectangle(0, 0, image.Width, image.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, image.PixelFormat); var dataStream = new DataStream(imageData.Scan0, imageData.Stride * imageData.Height, true, false); var properties = new BitmapProperties { PixelFormat = new SharpDX.Direct2D1.PixelFormat { Format = SharpDX.DXGI.Format.B8G8R8A8_UNorm, AlphaMode = AlphaMode.Premultiplied } }; //Load the image from the gdi resource var bitmapDirect2D = new Bitmap(rt, new Size2(image.Width, image.Height), dataStream, imageData.Stride, properties); image.UnlockBits(imageData); return(bitmapDirect2D); } // GetDirect2DBitmapWithSharpDX()
/// <summary> /// Updates the specified <see cref="IImage" /> in the manager, creating the <see cref="Bitmap" /> for it. /// </summary> /// <param name="image">The image.</param> /// <returns>The updated brush.</returns> public Bitmap Update(IImage image) { if (image == null) { throw new ArgumentNullException(nameof(image)); } lock (_lock) { if (_bitmaps == null) { throw new ObjectDisposedException(nameof(DirectXResourceManager)); } return(_bitmaps.AddOrUpdate( image, CreateBitmap, (k, b) => { Bitmap newBitmap = CreateBitmap(k); b.Dispose(); return newBitmap; }, false)); } }
public void Reset(D2DDeviceContext d2dContext) { blackBrush?.Dispose(); whiteBrush?.Dispose(); bmToolBarBox?.Dispose(); bmToolBarSelect?.Dispose(); // textFormat?.Dispose(); d2dDeviceContext = d2dContext; blackBrush = new SolidColorBrush(d2dContext, Color.Black); whiteBrush = new SolidColorBrush(d2dContext, Color.White); bmToolBarBox = D2DBitmap.FromWicBitmap( d2dContext, bsToolBarBox, new BitmapProperties( new PixelFormat(SharpDX.DXGI.Format.R8G8B8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied) )); bmToolBarSelect = D2DBitmap.FromWicBitmap( d2dContext, bsToolBarSelect, new BitmapProperties( new PixelFormat(SharpDX.DXGI.Format.R8G8B8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied) )); }
public Bitmap ConvertBitmap(System.Drawing.Bitmap bmp) { System.Drawing.Imaging.BitmapData bmpData = bmp.LockBits( new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppPArgb); DataStream stream = new DataStream(bmpData.Scan0, bmpData.Stride * bmpData.Height, true, false); PixelFormat pFormat = new PixelFormat(Format.B8G8R8A8_UNorm, AlphaMode.Premultiplied); BitmapProperties bmpProps = new BitmapProperties(pFormat); Bitmap result = new Bitmap( renderTarget, new Size2(bmp.Width, bmp.Height), stream, bmpData.Stride, bmpProps); bmp.UnlockBits(bmpData); stream.Dispose(); bmp.Dispose(); return(result); }
/// <summary> /// Creates a Direct2D bitmap from a GDI bitmap for the specified rendering target /// </summary> /// <param name="bitmap">Original bitmap</param> /// <param name="renderTarget">Destination rendering target</param> /// <param name="disposeOriginal">Whether or not to release the resources of the GDI bitmap</param> /// <returns>A Direct2D bitmap instance the caller is responsible for disposal</returns> public static Bitmap ToDirect2DBitmap( this System.Drawing.Bitmap bitmap, RenderTarget renderTarget, bool disposeOriginal = true) { // lock bits from the original bitmap so we can read its data BitmapData data = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppPArgb); // copy GDI bitmap data to Direct2D one var stream = new DataStream(data.Scan0, data.Stride * data.Height, true, false); var format = new SharpDX.Direct2D1.PixelFormat(Format.B8G8R8A8_UNorm, AlphaMode.Premultiplied); var props = new BitmapProperties(format); // create Direct2D bitmap and release resources var direct2DBitmap = new Bitmap(renderTarget, new Size2(bitmap.Width, bitmap.Height), stream, data.Stride, props); // release resources stream.Dispose(); bitmap.UnlockBits(data); if (disposeOriginal) { bitmap.Dispose(); } // return new bitmap return(direct2DBitmap); }
/// <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(); } } } } } }
public static Bitmap Decode(RenderTarget device, BitmapDecoder decoder) { var frame = decoder.GetFrame(0); var converter = new FormatConverter(Image.ImageFactory); foreach (var format in _pixelFormatEnumerator) { try { converter.Initialize(frame, format); var bmp = Bitmap.FromWicBitmap(device, converter); TryCatch(() => converter.Dispose()); TryCatch(() => frame.Dispose()); return(bmp); } catch { TryCatch(() => converter.Dispose()); converter = new FormatConverter(Image.ImageFactory); } } TryCatch(() => converter.Dispose()); TryCatch(() => frame.Dispose()); throw new Exception("Unsupported Image Format!"); }
private static Bitmap LoadBitmapFromMemory(RenderTarget device, byte[] bytes) { if (device == null) { throw new ArgumentNullException(nameof(device)); } if (bytes == null) { throw new ArgumentNullException(nameof(bytes)); } if (bytes.Length == 0) { throw new ArgumentOutOfRangeException(nameof(bytes)); } Bitmap bmp = null; MemoryStream stream = null; BitmapDecoder decoder = null; BitmapFrameDecode frame = null; FormatConverter converter = null; try { stream = new MemoryStream(bytes); decoder = new BitmapDecoder(ImageFactory, stream, DecodeOptions.CacheOnDemand); bmp = ImageDecoder.Decode(device, decoder); decoder.Dispose(); stream.Dispose(); return(bmp); } catch { if (converter?.IsDisposed == false) { converter.Dispose(); } if (frame?.IsDisposed == false) { frame.Dispose(); } if (decoder?.IsDisposed == false) { decoder.Dispose(); } if (stream != null) { TryCatch(() => stream.Dispose()); } if (bmp?.IsDisposed == false) { bmp.Dispose(); } throw; } }
public unsafe void UpdateData(Image image) { if ((image is System.Drawing.Bitmap) == false) return; lock(mData) { if(image.Width != mWidth || image.Height != mHeight) { if (mBitmap != null) mBitmap.Dispose(); mData.Dispose(); mData = new DataStream(image.Width * image.Height * 4, true, true); mWidth = image.Width; mHeight = image.Height; mBitmap = new Bitmap(InterfaceManager.Instance.Surface.RenderTarget, new Size2(mWidth, mHeight), mProperties); } mData.Position = 0; var data = new byte[mWidth * mHeight * 4]; fixed(byte* ptr = data) { var bmp = (System.Drawing.Bitmap)image; var bmpd = bmp.LockBits(new System.Drawing.Rectangle(0, 0, mWidth, mHeight), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); UnsafeNativeMethods.CopyMemory(ptr, (byte*)bmpd.Scan0.ToPointer(), mWidth * mHeight * 4); bmp.UnlockBits(bmpd); } if(mProperties.PixelFormat.AlphaMode == AlphaMode.Premultiplied) { for(var i = 0; i < mWidth * mHeight * 4; i += 4) { data[i] = (byte) (data[i] * data[i + 3] / 255.0f); data[i + 1] = (byte) (data[i + 1] * data[i + 3] / 255.0f); data[i + 2] = (byte) (data[i + 2] * data[i + 3] / 255.0f); } } mBitmap.CopyFromMemory(data, mWidth * 4); } }
public void RenderSegment(Anvil anvil, RenderTarget renderTarget, out ChunkEntry output) { // create char array to hold rendered blocks int[] drawnChunk = new int[16 * 16]; // x * z * 4 where 4 is colors // render code here foreach (AnvilSection section in anvil.Sections) { // render blocks for (int y = 0; y < 16; y++) { for (int z = 0; z < 16; z++) { for (int x = 0; x < 16; x++) { int index = y * 256 + z * 16 + x; int dindex = z * 16 + x; byte blockId = section.Blocks[index]; if (blockId == 0 || !theBlocks.BlockList.ContainsKey(blockId)) continue; var blockCol = theBlocks.BlockList[blockId]; var finalCol = new byte[4]; var prevCol = BitConverter.GetBytes(drawnChunk[dindex]); finalCol[0] = processAlpha(blockCol[0], prevCol[0], blockCol[3] / 255.0f); finalCol[1] = processAlpha(blockCol[1], prevCol[1], blockCol[3] / 255.0f); finalCol[2] = processAlpha(blockCol[2], prevCol[2], blockCol[3] / 255.0f); finalCol[3] = 255; drawnChunk[dindex] = BitConverter.ToInt32(finalCol, 0); } } } } // render heightmap for (int z = 0; z < 16; z++) { for (int x = 0; x < 16; x++) { int dindex = z * 16 + x; var value = (byte)MathUtil.Clamp((anvil.HeightMap[z * 16 + x] - 64) * 2, 0, 255); var finalCol = new byte[4]; var prevCol = BitConverter.GetBytes(drawnChunk[dindex]); finalCol[0] = processAlpha(255, prevCol[0], value / 255.0f); finalCol[1] = processAlpha(255, prevCol[1], value / 255.0f); finalCol[2] = processAlpha(255, prevCol[2], value / 255.0f); finalCol[3] = 255; drawnChunk[dindex] = BitConverter.ToInt32(finalCol, 0); } } Bitmap newBitmap = new Bitmap(renderTarget, new DrawingSize(16, 16), new BitmapProperties() { PixelFormat = new PixelFormat(Format.R8G8B8A8_UNorm, AlphaMode.Premultiplied) }); newBitmap.CopyFromMemory(drawnChunk, 16 * 4); output = new ChunkEntry { XPos = anvil.XPos, ZPos = anvil.ZPos, RenderedChunk = newBitmap }; }
public override void Load(CanvasRenderArguments args) { // set the properties of the image BitmapProperties bitmapProps = new BitmapProperties(); bitmapProps.PixelFormat = new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, AlphaMode.Premultiplied); if (mImageBitmap == null) { // make the bitmap for Direct2D1 mImageBitmap = new SharpDX.Direct2D1.Bitmap(args.renderTarget, new Size2(Width, Height), bitmapProps); } // write to the specific bitmap not create a new one mImageBitmap.CopyFromMemory(internalImage, Pitch); }
internal static Bitmap ToSharpDXBitmap(RenderTarget rt, System.Drawing.Bitmap image, float symbolScale) { if (image == null) throw new ArgumentNullException("image"); if (image.PixelFormat != GdiPixelFormat.Format32bppPArgb) return null; var imageData = image.LockBits(new System.Drawing.Rectangle(0, 0, image.Width, image.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, image.PixelFormat); var dataStream = new DataStream(imageData.Scan0, imageData.Stride*imageData.Height, true, false); var properties = new BitmapProperties { PixelFormat = new SharpDX.Direct2D1.PixelFormat { Format = SharpDX.DXGI.Format.B8G8R8A8_UNorm, AlphaMode = AlphaMode.Premultiplied } }; // ToDo apply scaling here! //var scaler = new BitmapScaler(rt.Factory.NativePointer); //scaler. //Load the image from the gdi resource var result = new Bitmap(rt, new Size2(image.Width, image.Height), dataStream, imageData.Stride, properties); image.UnlockBits(imageData); return result; }
protected override void Initialize(DemoConfiguration demoConfiguration) { base.Initialize(demoConfiguration); _bitmap = LoadFromFile(RenderTarget2D, "sharpdx.png"); }
public void UpdateInternalImage(Matrix.FxMatrixF mat, ColorMap map, bool useInvMap = false) { // link the extran matrix with the internal internalMatrix = mat; // check if we need to create a new internal buffer if (mat.Width != Width || mat.Height != Height) { lock (this) { // set the properties of the image BitmapProperties bitmapProps = new BitmapProperties(); bitmapProps.PixelFormat = new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, AlphaMode.Premultiplied); // set the size of the image Width = mat.Width; Height = mat.Height; if (mImageBitmap != null) { mImageBitmap.Dispose(); } // make the bitmap for Direct2D1 mImageBitmap = new SharpDX.Direct2D1.Bitmap(this.Parent.RenderVariables.renderTarget, new Size2(Width, Height), bitmapProps); } } unsafe { try { int size = Width * Height; fixed (byte* dst = internalImage) { fixed (float* src = mat.Data) { byte* pDst = dst; float* pSrc = src; if (useInvMap) { #if false float* pSrcEnd = pSrc + mat.Size; for (; pSrc < pSrcEnd; pSrc++) { byte id = (byte)(255 - *(pSrc) * 255); *(pDst++) = map[id, 2]; *(pDst++) = map[id, 1]; *(pDst++) = map[id, 0]; *(pDst++) = 255; } #else int step = size / 8; Parallel.For(0, 8, (s) => { int end = (s + 1) * step; for (int i = s * step; i < end; i++) { byte id = (byte)(255 - *(pSrc + i) * 255); int i4 = i * 4; *(pDst + i4) = map[id, 2]; *(pDst + i4 + 1) = map[id, 1]; *(pDst + i4 + 2) = map[id, 0]; *(pDst + i4 + 3) = 255; } }); #endif } else { #if false float* pSrcEnd = pSrc + mat.Size; for(; pSrc < pSrcEnd; pSrc++) { byte id = (byte)(*(pSrc) * 255); *(pDst++) = map[id, 2]; *(pDst++) = map[id, 1]; *(pDst++) = map[id, 0]; *(pDst++) = 255; } #else int step = size / 8; Parallel.For(0, 8, (s) => { int end = (s + 1) * step; for (int i = s * step; i < end; i++) { byte id = (byte)(*(pSrc + i) * 255); int i4 = i * 4; *(pDst + i4) = map[id, 2]; *(pDst + i4 + 1) = map[id, 1]; *(pDst + i4 + 2) = map[id, 0]; *(pDst + i4 + 3) = 255; } }); #endif } } } // write to the specific bitmap not create a new one mImageBitmap.CopyFromMemory(internalImage, Width * 4); } catch (Exception ex) { Console.WriteLine(ex.Message); } } }
protected override void OnDraw(SharpDX.Direct2D1.WindowRenderTarget device) { if (once) { System.Drawing.Bitmap bmp = (System.Drawing.Bitmap)Resources.ResourceManager.GetObject("ranks"); try { this.ranksBmp = SDXBitmapFromSysBitmap(device, bmp); once = false; } catch { } } csgo = (CSGOImplementation)Program.GameImplementation; Player currentPlayer = csgo.GetCurrentPlayer(); if (csgo.SignOnState < SignOnState.SIGNONSTATE_PRESPAWN || csgo.SignOnState > SignOnState.SIGNONSTATE_FULL) return; if (csgo.Players == null) return; if (csgo.Players.Length == 0) return; if (currentPlayer == null) return; if (csgo.GetValue<YesNo>("espEnabled") == YesNo.No) return; try { DrawWorld(device, csgo); } catch { } try { foreach (Player player in csgo.Players) DrawPlayer(device, currentPlayer, player); foreach (Entity entity in csgo.Entities) DrawEntity(device, currentPlayer, entity); for (int i = csgo.Damages.Count - 1; i >= 0; i--) DrawDamage(device, currentPlayer, csgo.Damages[i]); } catch { } //DrawPunchAngles(device, csgo); }
public Bitmap GetBitmap() { lock(mData) { if (mBitmap == null) mBitmap = new Bitmap(InterfaceManager.Instance.Surface.RenderTarget, new Size2(mWidth, mHeight), mProperties); if (!mChanged) return mBitmap; mBitmap.CopyFromMemory(mData.DataPointer, mWidth * 4); mChanged = false; } return mBitmap; }
/// <summary> /// Initializes a new DirectXTexture class. /// </summary> /// <param name="bmp">The Bitmap.</param> internal DirectXTexture(System.Drawing.Bitmap bmp) { RawBitmap = (System.Drawing.Bitmap) bmp.Clone(); _width = bmp.Width; _height = bmp.Height; var sourceArea = new Rectangle(0, 0, bmp.Width, bmp.Height); var bitmapProperties = new BitmapProperties( new PixelFormat(Format.R8G8B8A8_UNorm, AlphaMode.Premultiplied), 96, 96); var size = new Size2(bmp.Width, bmp.Height); int stride = bmp.Width*sizeof (int); using (var tempStream = new DataStream(bmp.Height*stride, true, true)) { BitmapData bitmapData = bmp.LockBits(sourceArea, ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppPArgb); for (int y = 0; y < bmp.Height; y++) { int offset = bitmapData.Stride*y; for (int x = 0; x < bmp.Width; x++) { byte b = Marshal.ReadByte(bitmapData.Scan0, offset++); byte g = Marshal.ReadByte(bitmapData.Scan0, offset++); byte r = Marshal.ReadByte(bitmapData.Scan0, offset++); byte a = Marshal.ReadByte(bitmapData.Scan0, offset++); int rgba = r | (g << 8) | (b << 16) | (a << 24); tempStream.Write(rgba); } } bmp.UnlockBits(bitmapData); tempStream.Position = 0; _bmp = new Bitmap(DirectXHelper.RenderTarget, size, tempStream, stride, bitmapProperties); } }