internal static D2DBitmap LoadBitmapFromStream( RenderTarget renderTarget, ImagingFactory wicFactory, Stream ioStream) { BitmapDecoder decoder = wicFactory.CreateDecoderFromStream(ioStream, DecodeMetadataCacheOption.OnLoad); return CreateBitmapFromDecoder(renderTarget, wicFactory, decoder); }
private static ImagingFactory GetFactory() { if (m_factory == null) { m_factory = new ImagingFactory(); } return m_factory; }
internal static D2DBitmap LoadBitmapFromFile( RenderTarget renderTarget, ImagingFactory wicFactory, string fileName) { BitmapDecoder decoder = wicFactory.CreateDecoderFromFileName(fileName, DesiredAccess.Read, DecodeMetadataCacheOption.OnLoad); return CreateBitmapFromDecoder(renderTarget, wicFactory, decoder); }
/// <summary> /// Creates a ShaderResourceView from a bitmap in a Stream. /// </summary> /// <param name="device">The Direct3D device that will own the ShaderResourceView</param> /// <param name="stream">Any Windows Imaging Component decodable image</param> /// <returns>A ShaderResourceView object with the loaded texture.</returns> public static ShaderResourceView LoadTexture( D3DDevice device, Stream stream ) { ImagingFactory factory = new ImagingFactory( ); BitmapDecoder bitmapDecoder = factory.CreateDecoderFromStream( stream, DecodeMetadataCacheOptions.OnDemand ); return LoadFromDecoder(device, factory, bitmapDecoder); }
/// <summary> /// Creates a ShaderResourceView from a bitmap in a file. /// </summary> /// <param name="device">The Direct3D device that will own the ShaderResourceView</param> /// <param name="filePath">Any Windows Imaging Component decodable image</param> /// <returns>A ShaderResourceView object with the loaded texture.</returns> public static ShaderResourceView LoadTexture(D3DDevice device, String filePath) { ImagingFactory factory = new ImagingFactory(); BitmapDecoder bitmapDecoder = factory.CreateDecoderFromFilename( filePath, DesiredAccess.Read, DecodeMetadataCacheOptions.OnDemand); return LoadFromDecoder(device, factory, bitmapDecoder); }
public ImageInlineObject(RenderTarget renderTarget, ImagingFactory wicFactory, string resourceName) { _renderTarget = renderTarget; using (Stream stream = Application.ResourceAssembly.GetManifestResourceStream(resourceName)) { _bitmap = BitmapUtilities.LoadBitmapFromStream(renderTarget, wicFactory, stream); // Save the bitmap size, for faster access _bitmapSize = _bitmap.Size; } }
private static D2DBitmap CreateBitmapFromDecoder(RenderTarget renderTarget, ImagingFactory wicFactory, BitmapDecoder decoder) { BitmapFrameDecode source; FormatConverter converter; // Create the initial frame. source = decoder.GetFrame(0); // Convert the image format to 32bppPBGRA -- which Direct2D expects. converter = wicFactory.CreateFormatConverter(); converter.Initialize( source.ToBitmapSource(), PixelFormats.Pbgra32Bpp, BitmapDitherType.None, BitmapPaletteType.MedianCut ); // Create a Direct2D bitmap from the WIC bitmap. return renderTarget.CreateBitmapFromWicBitmap( converter.ToBitmapSource()); }
private void CreateDeviceIndependentResources() { // Create the D2D Factory d2dFactory = D2DFactory.CreateFactory(D2DFactoryType.SingleThreaded); // Create the DWrite Factory dwriteFactory = DWriteFactory.CreateFactory(); wicFactory = new ImagingFactory(); string text = "Inline Object * Sample"; textFormat = dwriteFactory.CreateTextFormat("Gabriola", 72); textFormat.TextAlignment = DWrite.TextAlignment.Center; textFormat.ParagraphAlignment = DWrite.ParagraphAlignment.Center; textLayout = dwriteFactory.CreateTextLayout( text, textFormat, (float) host.ActualWidth, (float) host.ActualHeight); }
protected override List <NativeItemData> BuildNativeControlItems() { var retVal = new List <NativeItemData>(Items.Count); if (Items != null) { for (int i = 0; i < Items.Count; i++) { IImagingFactory newImagingFactory = ImagingFactory.GetImaging(); IImage newIImage; if (Items[i].IsAvatarLoaded) { newImagingFactory.CreateImageFromFile(Items[i].Avatar, out newIImage); } else { newIImage = MasterForm.SkinManager.GetImage("AvatarStub"); } NativeItemData newNativeItemData = new KineticListView <WallPostListViewItem> .NativeItemData { PrimaryText = Items[i].UserName, SecondaryText = Items[i].Status, TertiaryText = Items[i].StatusChangeDate, PrimaryImage = newIImage, InfoLeftIndents = new int[2], InfoTopIndents = new int[1] }; retVal.Add(newNativeItemData); } } #region старая версия //if (Items != null) //{ // for (int i = 0; i < Items.Count; i++) // { // IImagingFactory iImagingFactory = ImagingFactory.GetImaging(); // //Привязка аватарки пользователя, если она еще не загружена, выводится заглушка // IImage primaryImage; // if (Items[i].IsAvatarLoaded) // iImagingFactory.CreateImageFromFile(Items[i].Avatar, out primaryImage); // else // primaryImage = MasterForm.SkinManager.GetImage("AvatarStub"); // //Значек подарка или online // /* // IImage secondaryImage; // if (Items[i].IsBirthday) // secondaryImage = MasterForm.SkinManager.GetImage("Birthday"); // else if (Items[i].StatusOnline) // secondaryImage = MasterForm.SkinManager.GetImage("Online"); // else secondaryImage = null; // */ // //Статус пользователя // string status = Items[i].Status; // NativeItemData data = new NativeItemData // { // PrimaryText = Items[i].Name, // SecondaryText = status, // Tag = Items[i].Name, // PrimaryImage = primaryImage, // //SecondaryImage = secondaryImage, // InfoLeftIndents = new int[2], // InfoTopIndents = new int[1] // }; // retVal.Add(data); // } //} #endregion return(retVal); }
private static MyRenderDeviceSettings CreateDeviceInternal(IntPtr windowHandle, MyRenderDeviceSettings?settingsToTry) { if (Device != null) { Device.Dispose(); Device = null; } WIC = null; if (settingsToTry != null) { Log.WriteLine("CreateDevice - original settings"); Log.IncreaseIndent(); var originalSettings = settingsToTry.Value; LogSettings(ref originalSettings); } FeatureLevel[] featureLevels = { FeatureLevel.Level_11_0 }; DeviceCreationFlags flags = DeviceCreationFlags.None; #if DEBUG if (VRage.MyCompilationSymbols.DX11Debug) { flags |= DeviceCreationFlags.Debug; } #endif #if !XB1 WinApi.DEVMODE mode = new WinApi.DEVMODE(); WinApi.EnumDisplaySettings(null, WinApi.ENUM_REGISTRY_SETTINGS, ref mode); var settings = settingsToTry ?? new MyRenderDeviceSettings() { AdapterOrdinal = -1, BackBufferHeight = mode.dmPelsHeight, BackBufferWidth = mode.dmPelsWidth, WindowMode = MyWindowModeEnum.Fullscreen, RefreshRate = 60000, VSync = false, }; #else var settings = CreateXB1Settings(); #endif settings.AdapterOrdinal = ValidateAdapterIndex(settings.AdapterOrdinal); if (settings.AdapterOrdinal == -1) { throw new MyRenderException("No supported device detected!", MyRenderExceptionEnum.GpuNotSupported); } m_settings = settings; Log.WriteLine("CreateDevice settings"); Log.IncreaseIndent(); LogSettings(ref m_settings); // If this line crashes cmd this: Dism /online /add-capability /capabilityname:Tools.Graphics.DirectX~~~~0.0.1.0 var adapters = GetAdaptersList(); if (m_settings.AdapterOrdinal >= adapters.Length) { throw new MyRenderException("No supported device detected!", MyRenderExceptionEnum.GpuNotSupported); } var adapterId = adapters[m_settings.AdapterOrdinal].AdapterDeviceId; if (adapterId >= GetFactory().Adapters.Length) { throw new MyRenderException("Invalid adapter id binding!", MyRenderExceptionEnum.GpuNotSupported); } var adapter = GetFactory().Adapters[adapterId]; TweakSettingsAdapterAdHoc(adapter); Device = new Device(adapter, flags, FeatureLevel.Level_11_0); WIC = new ImagingFactory(); // HACK: This is required for Steam overlay to work. Apparently they hook only CreateDevice methods with DriverType argument. try { using (new Device(DriverType.Hardware, flags, FeatureLevel.Level_11_0)){} } catch { } InitDebugOutput(); if (DeviceContext != null) { DeviceContext.Dispose(); DeviceContext = null; } DeviceContext = Device.ImmediateContext; m_windowHandle = windowHandle; m_resolution = new Vector2I(m_settings.BackBufferWidth, m_settings.BackBufferHeight); if (!m_initializedOnce) { InitSubsystemsOnce(); m_initializedOnce = true; } if (!m_initialized) { OnDeviceReset(); InitSubsystems(); m_initialized = true; } if (m_swapchain != null) { m_swapchain.Dispose(); m_swapchain = null; } if (m_swapchain == null) { SharpDX.DXGI.Device d = Device.QueryInterface <SharpDX.DXGI.Device>(); Adapter a = d.GetParent <Adapter>(); var factory = a.GetParent <Factory>(); var scDesc = new SwapChainDescription(); scDesc.BufferCount = MyRender11Constants.BUFFER_COUNT; scDesc.Flags = SwapChainFlags.AllowModeSwitch; scDesc.IsWindowed = true; scDesc.ModeDescription.Format = MyRender11Constants.DX11_BACKBUFFER_FORMAT; scDesc.ModeDescription.Height = m_settings.BackBufferHeight; scDesc.ModeDescription.Width = m_settings.BackBufferWidth; scDesc.ModeDescription.RefreshRate.Numerator = m_settings.RefreshRate; scDesc.ModeDescription.RefreshRate.Denominator = 1000; scDesc.ModeDescription.Scaling = DisplayModeScaling.Unspecified; scDesc.ModeDescription.ScanlineOrdering = DisplayModeScanlineOrder.Progressive; scDesc.SampleDescription.Count = 1; scDesc.SampleDescription.Quality = 0; scDesc.OutputHandle = m_windowHandle; scDesc.Usage = Usage.RenderTargetOutput; scDesc.SwapEffect = SwapEffect.Discard; m_swapchain = new SwapChain(factory, Device, scDesc); m_swapchain.GetParent <Factory>().MakeWindowAssociation(m_windowHandle, WindowAssociationFlags.IgnoreAll); } // we start with window always (DXGI recommended) m_settings.WindowMode = MyWindowModeEnum.Window; ApplySettings(settings); return(m_settings); }
private void LoadDeviceIndependentResource() { // Create the D2D Factory // This really needs to be set to type MultiThreaded if rendering is to be performed by multiple threads, // such as if used in a control similar to DirectControl sample control where rendering is done by a dedicated render thread, // especially if multiple such controls are used in one application, but also when multiple applications use D2D Factories. // // In this sample - SingleThreaded type is used because rendering is only done by the main/UI thread and only when required // (when the surface gets invalidated) making the risk of synchronization problems - quite low. d2dFactory = D2DFactory.CreateFactory(D2DFactoryType.Multithreaded); // Create the DWrite Factory dwriteFactory = DWriteFactory.CreateFactory(); // Create the WIC Factory wicFactory = ImagingFactory.Create(); TextBoxStroke = d2dFactory.CreateStrokeStyle( new StrokeStyleProperties( CapStyle.Flat, CapStyle.Flat, CapStyle.Round, LineJoin.Miter, 5.0f, DashStyle.Dash, 3f), null); }
public BitmapImpl(ImagingFactory imagingFactory) { WicImagingFactory = imagingFactory; }
public static BitmapBrush makeBitmapBrush(RenderTarget renderTarget, string imgName, bool blankImage = false) { string imageSrc = Program.spriteFileDir + imgName; if (blankImage) { var pf = new SharpDX.Direct2D1.PixelFormat() { AlphaMode = SharpDX.Direct2D1.AlphaMode.Premultiplied, Format = Format.B8G8R8A8_UNorm }; BitmapRenderTarget pallete = new BitmapRenderTarget(renderTarget, CompatibleRenderTargetOptions.GdiCompatible, pf); return(new BitmapBrush(renderTarget, pallete.Bitmap, new BitmapBrushProperties() { ExtendModeX = ExtendMode.Wrap, ExtendModeY = ExtendMode.Wrap })); } if (File.Exists(imageSrc)) { ImagingFactory imagingFactory = new ImagingFactory(); NativeFileStream fileStream = new NativeFileStream(imageSrc, NativeFileMode.Open, NativeFileAccess.Read); BitmapDecoder bitmapDecoder = new BitmapDecoder(imagingFactory, fileStream, DecodeOptions.CacheOnDemand); BitmapFrameDecode frame = bitmapDecoder.GetFrame(0); FormatConverter converter = new FormatConverter(imagingFactory); converter.Initialize(frame, SharpDX.WIC.PixelFormat.Format32bppPRGBA); Bitmap bitmap = Bitmap.FromWicBitmap(renderTarget, converter); Utilities.Dispose(ref bitmapDecoder); Utilities.Dispose(ref fileStream); Utilities.Dispose(ref imagingFactory); Utilities.Dispose(ref converter); return(new BitmapBrush(renderTarget, bitmap, new BitmapBrushProperties() { ExtendModeX = ExtendMode.Wrap, ExtendModeY = ExtendMode.Wrap })); } else { Console.WriteLine("{0} missing", imageSrc); var pf = new SharpDX.Direct2D1.PixelFormat() { AlphaMode = SharpDX.Direct2D1.AlphaMode.Premultiplied, Format = Format.B8G8R8A8_UNorm }; BitmapRenderTarget pallete = new BitmapRenderTarget(renderTarget, CompatibleRenderTargetOptions.GdiCompatible, new Size2F(30f, 30f), new Size2(1, 1), pf); pallete.BeginDraw(); pallete.Clear(Color.Purple); pallete.EndDraw(); return(new BitmapBrush(renderTarget, pallete.Bitmap, new BitmapBrushProperties() { ExtendModeX = ExtendMode.Wrap, ExtendModeY = ExtendMode.Wrap })); } }
public WicBitmapDecoder(ImagingFactory factory, BitmapContainerFormat format) { this.factory = factory; this.wicImpl = new BitmapDecoder(factory, FormatGuids[(int)format]); }
private static ShaderResourceView LoadFromDecoder(D3DDevice device, ImagingFactory factory, BitmapDecoder bitmapDecoder) { if (bitmapDecoder.FrameCount == 0) throw new ArgumentException("Image file successfully loaded, but it has no image frames."); BitmapFrameDecode bitmapFrameDecode = bitmapDecoder.GetFrame(0); BitmapSource bitmapSource = bitmapFrameDecode.ToBitmapSource(); // create texture description Texture2DDescription textureDescription = new Texture2DDescription() { Width = bitmapSource.Size.Width, Height = bitmapSource.Size.Height, MipLevels = 1, ArraySize = 1, Format = Format.R8G8B8A8_UNORM, SampleDescription = new SampleDescription() { Count = 1, Quality = 0, }, Usage = Usage.Dynamic, BindFlags = BindFlag.ShaderResource, CpuAccessFlags = CpuAccessFlag.Write, MiscFlags = 0 }; // create texture Texture2D texture = device.CreateTexture2D(textureDescription); // Create a format converter WICFormatConverter converter = factory.CreateFormatConverter(); converter.Initialize( bitmapSource, PixelFormats.Pf32bppRGBA, BitmapDitherType.None, BitmapPaletteType.Custom); // get bitmap data byte[] buffer = converter.CopyPixels(); // Copy bitmap data to texture MappedTexture2D texmap = texture.Map(0, Map.WriteDiscard, MapFlag.Unspecified); Marshal.Copy(buffer, 0, texmap.Data, buffer.Length); texture.Unmap(0); // create shader resource view description ShaderResourceViewDescription srvDescription = new ShaderResourceViewDescription() { Format = textureDescription.Format, ViewDimension = ShaderResourceViewDimension.Texture2D, Texture2D = new Texture2DShaderResourceView() { MipLevels = textureDescription.MipLevels, MostDetailedMip = 0 } }; // create shader resource view from texture return device.CreateShaderResourceView(texture, srvDescription); }
public WicBitmapSource(ImagingFactory factory, BitmapSource wicImpl) { this.factory = factory; this.WicImpl = wicImpl; }
// Returns the DXGI format and optionally the WIC pixel GUID to convert to. private static DataFormat DetermineFormat(ImagingFactory imagingFactory, Guid pixelFormat, WicFlags flags, out Guid convertGuid) { DataFormat format = ToFormat(pixelFormat); convertGuid = Guid.Empty; if (format == DataFormat.Unknown) { for (int i = 0; i < WICConvertTable.Length; ++i) { if (pixelFormat == WICConvertTable[i].Source) { convertGuid = WICConvertTable[i].Target; format = ToFormat(WICConvertTable[i].Target); Debug.Assert(format != DataFormat.Unknown); break; } } } // Handle special cases based on flags switch (format) { case DataFormat.B8G8R8A8_UNORM: // BGRA case DataFormat.B8G8R8X8_UNORM: // BGRX if ((flags & WicFlags.ForceRgb) != 0) { format = DataFormat.R8G8B8A8_UNORM; convertGuid = PixelFormat.Format32bppRGBA; } break; case DataFormat.R10G10B10_XR_BIAS_A2_UNORM: if ((flags & WicFlags.NoX2Bias) != 0) { format = DataFormat.R10G10B10A2_UNORM; convertGuid = PixelFormat.Format32bppRGBA1010102; } break; case DataFormat.B5G5R5A1_UNORM: case DataFormat.B5G6R5_UNORM: if ((flags & WicFlags.No16Bpp) != 0) { format = DataFormat.R8G8B8A8_UNORM; convertGuid = PixelFormat.Format32bppRGBA; } break; case DataFormat.R1_UNORM: if ((flags & WicFlags.FlagsAllowMono) == 0) { // By default we want to promote a black & white to grayscale since R1 is not a generally supported D3D format format = DataFormat.R8_UNORM; convertGuid = PixelFormat.Format8bppGray; } break; } return format; }
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); }
public WicBitmapEncoder(ImagingFactory factory, BitmapContainerFormat format) { this.wicImpl = new SharpDX.WIC.BitmapEncoder(factory, FormatGuids[(int)format]); }
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); }
public DxGraphicsWrapper(WindowRenderTarget renderTarget2D, SharpDX.DirectWrite.Factory factory2D, ImagingFactory imagingFactory) { _renderTarget2D = renderTarget2D; _factory2D = factory2D; _imagingFactory = imagingFactory; _solidColorBrushConverter = new ConverterAndCacher <SolidBrush, SolidColorBrush>( brush => new SolidColorBrush(_renderTarget2D, new SharpDX.Mathematics.Interop.RawColor4( r: ((float)brush.Color.R) / byte.MaxValue, g: ((float)brush.Color.G) / byte.MaxValue, b: ((float)brush.Color.B) / byte.MaxValue, a: 1 ) )); _textFormatConverterAndCacher = new ConverterAndCacher <Font, TextFormat>( f => new TextFormat(_factory2D, f.FontFamily.Name, f.Size)); }
public DecodedKinectCaptureFrame(Image image, KinectImageProvider provider) { this.imagingFactory = new ImagingFactory(); this.image = image; Provider = provider; }
private async Task SetImageAsync(StorageFile file) { if (file == null) { return; } this.currentFile = file; //// カラマネする場合 // モニタプロファイルのStreamを作成 // ※物理モニタがない環境だと例外を吐く var profileStream = await DisplayInformation.GetForCurrentView().GetColorProfileAsync(); // Stream → Bytes var profileBytes = new byte[profileStream.Size]; var reader = new DataReader(profileStream); await reader.LoadAsync((uint)profileStream.Size); reader.ReadBytes(profileBytes); // モニタプロファイルのColorContextを作成 var factory = new ImagingFactory(); // 割とあちこちで使う var displayProfile = new ColorContext(factory); displayProfile.InitializeFromMemory(DataStream.Create(profileBytes, true, false)); using (var stream = await currentFile.OpenAsync(FileAccessMode.Read)) { // デコーダーでファイルからフレームを取得 var decoder = new BitmapDecoder(factory, stream.AsStream(), DecodeOptions.CacheOnDemand); if (decoder.FrameCount < 1) { return; } var frame = decoder.GetFrame(0); // 埋め込みプロファイル取得 var srcColorContexts = frame.TryGetColorContexts(factory); var untaggedOrUnsupported = srcColorContexts == null || srcColorContexts.Length < 1; // プロファイルが読み込めなかった場合はsRGBとみなす var sourceProfile = !untaggedOrUnsupported ? srcColorContexts[0] : sRGBContext; SharpDX.WIC.BitmapSource transformSource = frame; if (untaggedOrUnsupported) { // プロファイルが読み込めなかった場合はsRGBを適用したいので、FormatConverterで32bppPBGRAへ変換 // 変換しなかった場合、色変換時にCMYK画像をsRGBとして扱ってしまうことでエラーが発生する var converter = new FormatConverter(factory); converter.Initialize(frame, PixelFormat.Format32bppPBGRA); transformSource = converter; } // ColorTransformを通すことで色変換ができる var transform = new ColorTransform(factory); transform.Initialize(transformSource, sourceProfile, displayProfile, PixelFormat.Format32bppPBGRA); var stride = transform.Size.Width * 4; // 横1行のバイト数 var size = stride * transform.Size.Height; var bytes = new byte[size]; transform.CopyPixels(bytes, stride); // Byte配列にピクセルデータをコピー // ピクセルデータをWriteableBitmapに書き込み var bitmap = new WriteableBitmap(transform.Size.Width, transform.Size.Height); using (var s = bitmap.PixelBuffer.AsStream()) { await s.WriteAsync(bytes, 0, size); } this.Image1.Source = bitmap; } ////// カラマネしない場合 //var bitmapImage = new BitmapImage(); //var fileStream = await file.OpenStreamForReadAsync(); //await bitmapImage.SetSourceAsync(fileStream.AsRandomAccessStream()); //this.Image1.Source = bitmapImage; }
private static TextureDescription DecodeMetadata(ImagingFactory imagingFactory, WicFlags flags, BitmapDecoder decoder, BitmapFrameDecode frame, out Guid pixelFormat) { var size = frame.Size; var description = new TextureDescription { Dimension = TextureDimension.Texture2D, Width = size.Width, Height = size.Height, Depth = 1, MipLevels = 1, ArraySize = (flags & WicFlags.AllFrames) != 0 ? decoder.FrameCount : 1, Format = DetermineFormat(imagingFactory, frame.PixelFormat, flags, out pixelFormat) }; if (description.Format == DataFormat.Unknown) throw new NotSupportedException("The pixel format is not supported."); if ((flags & WicFlags.IgnoreSrgb) == 0) { // Handle sRGB. #pragma warning disable 168 try { Guid containerFormat = decoder.ContainerFormat; var metareader = frame.MetadataQueryReader; if (metareader != null) { // Check for sRGB color space metadata. bool sRgb = false; if (containerFormat == ContainerFormatGuids.Png) { // Check for sRGB chunk. if (metareader.GetMetadataByName("/sRGB/RenderingIntent") != null) sRgb = true; } else if (containerFormat == ContainerFormatGuids.Jpeg) { if (Equals(metareader.GetMetadataByName("/app1/ifd/exif/{ushort=40961}"), 1)) sRgb = true; } else if (containerFormat == ContainerFormatGuids.Tiff) { if (Equals(metareader.GetMetadataByName("/ifd/exif/{ushort=40961}"), 1)) sRgb = true; } else { if (Equals(metareader.GetMetadataByName("System.Image.ColorSpace"), 1)) sRgb = true; } if (sRgb) description.Format = TextureHelper.MakeSRgb(description.Format); } } // ReSharper disable once EmptyGeneralCatchClause catch (Exception exception) { // Some formats just don't support metadata (BMP, ICO, etc.). } } #pragma warning restore 168 return description; }
/// <summary> /// Saves a texture to a stream as an image. /// </summary> /// <param name="texture">The texture to save.</param> /// <param name="imageFormat">The image format of the saved image.</param> /// <param name="imageResolutionInDpi">The image resolution in dpi.</param> /// <param name="toStream">The stream to save the texture to.</param> public static void SaveToStream(this Texture2D texture, System.Drawing.Imaging.ImageFormat imageFormat, double imageResolutionInDpi, System.IO.Stream toStream) { Texture2D textureCopy = null; ImagingFactory imagingFactory = null; Bitmap bitmap = null; BitmapEncoder bitmapEncoder = null; try { textureCopy = new Texture2D(texture.Device, new Texture2DDescription { Width = texture.Description.Width, Height = texture.Description.Height, MipLevels = 1, ArraySize = 1, Format = texture.Description.Format, Usage = ResourceUsage.Staging, SampleDescription = new SampleDescription(1, 0), BindFlags = BindFlags.None, CpuAccessFlags = CpuAccessFlags.Read, OptionFlags = ResourceOptionFlags.None }); texture.Device.CopyResource(texture, textureCopy); DataRectangle dataRectangle = textureCopy.Map(0, MapMode.Read, SharpDX.Direct3D10.MapFlags.None); imagingFactory = new ImagingFactory(); bitmap = new Bitmap( imagingFactory, textureCopy.Description.Width, textureCopy.Description.Height, PixelFormat.Format32bppBGRA, dataRectangle); toStream.Position = 0; if (imageFormat == System.Drawing.Imaging.ImageFormat.Png) { bitmapEncoder = new PngBitmapEncoder(imagingFactory, toStream); } else if (imageFormat == System.Drawing.Imaging.ImageFormat.Bmp) { bitmapEncoder = new BmpBitmapEncoder(imagingFactory, toStream); } else if (imageFormat == System.Drawing.Imaging.ImageFormat.Gif) { bitmapEncoder = new GifBitmapEncoder(imagingFactory, toStream); } else if (imageFormat == System.Drawing.Imaging.ImageFormat.Jpeg) { bitmapEncoder = new JpegBitmapEncoder(imagingFactory, toStream); } else if (imageFormat == System.Drawing.Imaging.ImageFormat.Tiff) { bitmapEncoder = new TiffBitmapEncoder(imagingFactory, toStream); } else { bitmapEncoder = new PngBitmapEncoder(imagingFactory, toStream); } using (var bitmapFrameEncode = new BitmapFrameEncode(bitmapEncoder)) { bitmapFrameEncode.Initialize(); bitmapFrameEncode.SetSize(bitmap.Size.Width, bitmap.Size.Height); var pixelFormat = PixelFormat.FormatDontCare; bitmapFrameEncode.SetPixelFormat(ref pixelFormat); bitmapFrameEncode.SetResolution(imageResolutionInDpi, imageResolutionInDpi); bitmapFrameEncode.WriteSource(bitmap); bitmapFrameEncode.Commit(); bitmapEncoder.Commit(); } } finally { bitmapEncoder?.Dispose(); textureCopy?.Unmap(0); textureCopy?.Dispose(); bitmap?.Dispose(); imagingFactory?.Dispose(); } }
/// <summary> /// SharpDX WIC sample. Encode to JPG and decode. /// </summary> static void Main() { const int width = 512; const int height = 512; const string filename = "output.jpg"; var factory = new ImagingFactory(); WICStream stream = null; // ------------------------------------------------------ // Encode a JPG image // ------------------------------------------------------ // Create a WIC outputstream if (File.Exists(filename)) { File.Delete(filename); } stream = new WICStream(factory, filename, NativeFileAccess.Write); // Initialize a Jpeg encoder with this stream var encoder = new JpegBitmapEncoder(factory); encoder.Initialize(stream); // Create a Frame encoder var bitmapFrameEncode = new BitmapFrameEncode(encoder); bitmapFrameEncode.Options.ImageQuality = 0.8f; bitmapFrameEncode.Initialize(); bitmapFrameEncode.SetSize(width, height); var guid = PixelFormat.Format24bppBGR; bitmapFrameEncode.SetPixelFormat(ref guid); // Write a pseudo-plasma to a buffer int stride = PixelFormat.GetStride(PixelFormat.Format24bppBGR, width); var bufferSize = height * stride; var buffer = new DataStream(bufferSize, true, true); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { buffer.WriteByte((byte)(x / 2.0 + 20.0 * Math.Sin(y / 40.0))); buffer.WriteByte((byte)(y / 2.0 + 30.0 * Math.Sin(x / 80.0))); buffer.WriteByte((byte)(x / 2.0)); } } // Copy the pixels from the buffer to the Wic Bitmap Frame encoder bitmapFrameEncode.WritePixels(512, new DataRectangle(buffer.DataPointer, stride)); // Commit changes bitmapFrameEncode.Commit(); encoder.Commit(); bitmapFrameEncode.Dispose(); encoder.Dispose(); stream.Dispose(); // ------------------------------------------------------ // Decode the previous JPG image // ------------------------------------------------------ // Read input stream = new WICStream(factory, filename, NativeFileAccess.Read); var decoder = new JpegBitmapDecoder(factory); decoder.Initialize(stream, DecodeOptions.CacheOnDemand); var bitmapFrameDecode = decoder.GetFrame(0); var queryReader = bitmapFrameDecode.MetadataQueryReader; // Dump MetadataQueryreader queryReader.Dump(Console.Out); queryReader.Dispose(); bitmapFrameDecode.Dispose(); decoder.Dispose(); stream.Dispose(); // Dispose factory.Dispose(); System.Diagnostics.Process.Start(Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, filename))); }
private static MyRenderDeviceSettings CreateDeviceInternal(IntPtr windowHandle, MyRenderDeviceSettings?settingsToTry, bool forceDebugDevice) { if (Device != null) { Device.Dispose(); Device = null; } WIC = null; if (settingsToTry != null) { Log.WriteLine("CreateDevice - original settings"); Log.IncreaseIndent(); var originalSettings = settingsToTry.Value; LogSettings(ref originalSettings); } FeatureLevel[] featureLevels = { FeatureLevel.Level_11_0 }; DeviceCreationFlags flags = DeviceCreationFlags.None; bool isEnabledDebugOutput = forceDebugDevice | MyCompilationSymbols.DX11Debug; if (isEnabledDebugOutput) { flags |= DeviceCreationFlags.Debug; } #if !XB1 var bounds = System.Windows.Forms.Screen.PrimaryScreen.Bounds; //var bounds = System.Windows.Forms.Screen.PrimaryScreen.Bounds; var settings = settingsToTry ?? new MyRenderDeviceSettings() { AdapterOrdinal = -1, BackBufferHeight = bounds.Width, BackBufferWidth = bounds.Height, WindowMode = MyWindowModeEnum.FullscreenWindow, RefreshRate = 60000, VSync = false, }; #else var settings = CreateXB1Settings(); #endif settings.AdapterOrdinal = ValidateAdapterIndex(settings.AdapterOrdinal); if (settings.AdapterOrdinal == -1) { throw new MyRenderException("No supported device detected!\nPlease apply windows updates and update to latest graphics drivers.", MyRenderExceptionEnum.GpuNotSupported); } m_settings = settings; Log.WriteLine("CreateDeviceInteral settings"); // If this line crashes cmd this: Dism /online /add-capability /capabilityname:Tools.Graphics.DirectX~~~~0.0.1.0 var factory = GetFactory(); var adapters = GetAdaptersList(); if (m_settings.AdapterOrdinal >= adapters.Length) { throw new MyRenderException("No supported device detected!\nPlease apply windows updates and update to latest graphics drivers.", MyRenderExceptionEnum.GpuNotSupported); } var adapterId = adapters[m_settings.AdapterOrdinal].AdapterDeviceId; if (adapterId >= factory.Adapters.Length) { throw new MyRenderException("Invalid adapter id binding!", MyRenderExceptionEnum.GpuNotSupported); } var adapter = factory.Adapters[adapterId]; Log.WriteLine("CreateDeviceInteral TweakSettingsAdapterAdHoc"); TweakSettingsAdapterAdHoc(adapter); if (m_settings.WindowMode == MyWindowModeEnum.Fullscreen && adapter.Outputs.Length == 0) { m_settings.WindowMode = MyWindowModeEnum.FullscreenWindow; } Log.IncreaseIndent(); LogSettings(ref m_settings); Log.WriteLine("CreateDeviceInteral create device"); if (MyCompilationSymbols.CreateRefenceDevice) { Device = new Device(DriverType.Reference, flags, FeatureLevel.Level_11_0); } else { Device = new Device(adapter, flags, FeatureLevel.Level_11_0); } Log.WriteLine("CreateDeviceInteral create ImagingFactory"); WIC = new ImagingFactory(); // HACK: This is required for Steam overlay to work. Apparently they hook only CreateDevice methods with DriverType argument. try { Log.WriteLine("CreateDeviceInteral Steam Overlay integration"); using (new Device(DriverType.Hardware, flags, FeatureLevel.Level_11_0)) { } Log.WriteLine("CreateDeviceInteral Steam Overlay OK"); } catch { Log.WriteLine("CreateDeviceInteral Steam Overlay Failed"); } Log.WriteLine("CreateDeviceInteral InitDebugOutput"); InitDebugOutput(isEnabledDebugOutput); Log.WriteLine("CreateDeviceInteral RC Dispose"); if (RC != null) { RC.Dispose(); RC = null; } Log.WriteLine("CreateDeviceInteral RC Create"); RC = new MyRenderContext(); Log.WriteLine("CreateDeviceInteral RC Initialize"); RC.Initialize(Device.ImmediateContext); m_windowHandle = windowHandle; m_resolution = new Vector2I(m_settings.BackBufferWidth, m_settings.BackBufferHeight); Log.WriteLine("CreateDeviceInteral m_initializedOnce (" + m_initializedOnce + ")"); if (!m_initializedOnce) { InitSubsystemsOnce(); m_initializedOnce = true; } Log.WriteLine("CreateDeviceInteral m_initialized (" + m_initialized + ")"); if (!m_initialized) { OnDeviceReset(); InitSubsystems(); m_initialized = true; } Log.WriteLine("CreateDeviceInteral m_swapchain (" + m_swapchain + ")"); if (m_swapchain != null) { m_swapchain.Dispose(); m_swapchain = null; } Log.WriteLine("CreateDeviceInteral create swapchain"); if (m_swapchain == null) { //SharpDX.DXGI.Device d = Device.QueryInterface<SharpDX.DXGI.Device>(); //Adapter a = d.GetParent<Adapter>(); //var factory = a.GetParent<Factory>(); var scDesc = new SwapChainDescription(); scDesc.BufferCount = MyRender11Constants.BUFFER_COUNT; scDesc.Flags = SwapChainFlags.AllowModeSwitch; scDesc.IsWindowed = true; scDesc.ModeDescription.Format = MyRender11Constants.DX11_BACKBUFFER_FORMAT; scDesc.ModeDescription.Height = m_settings.BackBufferHeight; scDesc.ModeDescription.Width = m_settings.BackBufferWidth; scDesc.ModeDescription.RefreshRate.Numerator = m_settings.RefreshRate; scDesc.ModeDescription.RefreshRate.Denominator = 1000; scDesc.ModeDescription.Scaling = DisplayModeScaling.Unspecified; scDesc.ModeDescription.ScanlineOrdering = DisplayModeScanlineOrder.Progressive; scDesc.SampleDescription.Count = 1; scDesc.SampleDescription.Quality = 0; scDesc.OutputHandle = m_windowHandle; scDesc.Usage = Usage.RenderTargetOutput; scDesc.SwapEffect = SwapEffect.Discard; try { m_swapchain = new SwapChain(factory, Device, scDesc); } catch (Exception ex) { Log.WriteLine("SwapChain factory = " + factory); Log.WriteLine("SwapChain Device = " + Device); Log.WriteLine("SwapChainDescription.BufferCount = " + scDesc.BufferCount); Log.WriteLine("SwapChainDescription.Flags = " + scDesc.Flags); Log.WriteLine("SwapChainDescription.ModeDescription.Format = " + scDesc.ModeDescription.Format); Log.WriteLine("SwapChainDescription.ModeDescription.Height = " + scDesc.ModeDescription.Height); Log.WriteLine("SwapChainDescription.ModeDescription.Width = " + scDesc.ModeDescription.Width); Log.WriteLine("SwapChainDescription.ModeDescription.RefreshRate.Numerator = " + scDesc.ModeDescription.RefreshRate.Numerator); Log.WriteLine("SwapChainDescription.ModeDescription.RefreshRate.Denominator = " + scDesc.ModeDescription.RefreshRate.Denominator); Log.WriteLine("SwapChainDescription.ModeDescription.Scaling = " + scDesc.ModeDescription.Scaling); Log.WriteLine("SwapChainDescription.ModeDescription.ScanlineOrdering = " + scDesc.ModeDescription.ScanlineOrdering); Log.WriteLine("SwapChainDescription.SampleDescription.Count = " + scDesc.SampleDescription.Count); Log.WriteLine("SwapChainDescription.SampleDescription.Quality = " + scDesc.SampleDescription.Quality); Log.WriteLine("SwapChainDescription.BufferCount = " + scDesc.BufferCount); Log.WriteLine("SwapChainDescription.Usage = " + scDesc.Usage); Log.WriteLine("SwapChainDescription.SwapEffect = " + scDesc.SwapEffect); throw ex; } factory.MakeWindowAssociation(m_windowHandle, WindowAssociationFlags.IgnoreAll); } // we start with window always (DXGI recommended) Log.WriteLine("CreateDeviceInteral Apply Settings"); m_settings.WindowMode = MyWindowModeEnum.Window; ApplySettings(settings); Log.WriteLine("CreateDeviceInteral done (" + m_settings + ")"); return(m_settings); }
/// <summary> /// Dispose of resources (IDisposable implementation) /// </summary> /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param> protected override void Dispose(bool disposing) { if (disposing && !disposed) { lock (renderSyncObject) { render = null; lock (sharedSyncObject) { if (sharedD2DFactory != null && d2DFactory == sharedD2DFactory) sharedRefCount--; if (d2DFactory != null && d2DFactory != sharedD2DFactory) d2DFactory.Dispose(); d2DFactory = null; if (dwriteFactory != null && dwriteFactory != sharedDwriteFactory) dwriteFactory.Dispose(); dwriteFactory = null; if (wicFactory != null && wicFactory != sharedWicFactory) wicFactory.Dispose(); wicFactory = null; if (sharedRefCount == 0) { if (sharedD2DFactory != null) sharedD2DFactory.Dispose(); sharedD2DFactory = null; if (sharedDwriteFactory != null) sharedDwriteFactory.Dispose(); sharedDwriteFactory = null; if (sharedWicFactory != null) sharedWicFactory.Dispose(); sharedWicFactory = null; } } foreach (DrawingShape shape in drawingShapes) { shape.Dispose(); } if (bitmap != null) bitmap.Dispose(); bitmap = null; if (dcRenderTarget != null) dcRenderTarget.Dispose(); dcRenderTarget = null; if (bitmapRenderTarget != null) bitmapRenderTarget.Dispose(); bitmapRenderTarget = null; if (hwndRenderTarget != null) hwndRenderTarget.Dispose(); hwndRenderTarget = null; disposed = true; } } base.Dispose(disposing); }
public WicTextureLoader(GraphicsDevice graphicsDevice) : base(graphicsDevice) { _wicFactory = new ImagingFactory(); }
public WicBitmapDecoder(ImagingFactory factory, Stream stream, DecodeOptions metadataOptions) { this.factory = factory; this.wicImpl = new BitmapDecoder(factory, stream, metadataOptions); }
public D3D11TextureManager(ID3D11Context renderContext) { this.renderContext = renderContext; this.imagingFactory = new ImagingFactory(); }
public static void AddPngImageResource(this ResourceLoader loader, string key, ImagingFactory factory, string filePath) => loader.AddResource(key, new PngImageResource(factory, filePath));
void CreateDeviceIndependentResources() { string msc_fontName = "Verdana"; float msc_fontSize = 50; string fps_fontName = "Courier New"; float fps_fontSize = 12; GeometrySink spSink; // Create D2D factory d2DFactory = D2DFactory.CreateFactory(D2DFactoryType.SingleThreaded); // Create WIC factory imagingFactory = ImagingFactory.Create(); // Create DWrite factory dWriteFactory = DWriteFactory.CreateFactory(); // Create DWrite text format object textFormat = dWriteFactory.CreateTextFormat( msc_fontName, msc_fontSize); textFormat.TextAlignment = Microsoft.WindowsAPICodePack.DirectX.DirectWrite.TextAlignment.Center; textFormat.ParagraphAlignment = Microsoft.WindowsAPICodePack.DirectX.DirectWrite.ParagraphAlignment.Center; // Create DWrite text format object textFormatFps = dWriteFactory.CreateTextFormat( fps_fontName, fps_fontSize); textFormatFps.TextAlignment = Microsoft.WindowsAPICodePack.DirectX.DirectWrite.TextAlignment.Leading; textFormatFps.ParagraphAlignment = Microsoft.WindowsAPICodePack.DirectX.DirectWrite.ParagraphAlignment.Near; // Create the path geometry. pathGeometry = d2DFactory.CreatePathGeometry(); // Write to the path geometry using the geometry sink. We are going to create an // hour glass. spSink = pathGeometry.Open(); spSink.SetFillMode(Microsoft.WindowsAPICodePack.DirectX.Direct2D1.FillMode.Alternate); spSink.BeginFigure( new Point2F(0, 0), FigureBegin.Filled ); spSink.AddLine(new Point2F(200, 0)); spSink.AddBezier( new BezierSegment( new Point2F(150, 50), new Point2F(150, 150), new Point2F(200, 200) )); spSink.AddLine( new Point2F(0, 200) ); spSink.AddBezier( new BezierSegment( new Point2F(50, 150), new Point2F(50, 50), new Point2F(0, 0) )); spSink.EndFigure( FigureEnd.Closed ); spSink.Close( ); }
public WritableWicBitmapImpl(ImagingFactory factory, int width, int height, PixelFormat?pixelFormat) : base(factory, width, height, pixelFormat) { }
public Texture2D LoadFromFile(Device device, ImagingFactory factory, string fileName) { using (var bs = LoadBitmap(factory, fileName)) return(CreateTexture2DFromBitmap(device, bs)); }
static MainPage() { factory = new ImagingFactory(); sRGBContext = new ColorContext(factory); sRGBContext.InitializeFromExifColorSpace(1); }
/// <summary> /// Dispose of resources (IDisposable implementation) /// </summary> /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param> protected override void Dispose(bool disposing) { if (disposing && !disposed) { lock (renderSyncObject) { render = null; lock (sharedSyncObject) { if (sharedD2DFactory != null && d2DFactory == sharedD2DFactory) { sharedRefCount--; } if (d2DFactory != null && d2DFactory != sharedD2DFactory) { d2DFactory.Dispose(); } d2DFactory = null; if (dwriteFactory != null && dwriteFactory != sharedDwriteFactory) { dwriteFactory.Dispose(); } dwriteFactory = null; if (wicFactory != null && wicFactory != sharedWicFactory) { wicFactory.Dispose(); } wicFactory = null; if (sharedRefCount == 0) { if (sharedD2DFactory != null) { sharedD2DFactory.Dispose(); } sharedD2DFactory = null; if (sharedDwriteFactory != null) { sharedDwriteFactory.Dispose(); } sharedDwriteFactory = null; if (sharedWicFactory != null) { sharedWicFactory.Dispose(); } sharedWicFactory = null; } } foreach (DrawingShape shape in drawingShapes) { shape.Dispose(); } if (bitmap != null) { bitmap.Dispose(); } bitmap = null; if (dcRenderTarget != null) { dcRenderTarget.Dispose(); } dcRenderTarget = null; if (bitmapRenderTarget != null) { bitmapRenderTarget.Dispose(); } bitmapRenderTarget = null; if (hwndRenderTarget != null) { hwndRenderTarget.Dispose(); } hwndRenderTarget = null; disposed = true; } } base.Dispose(disposing); }
private static ShaderResourceView LoadFromDecoder(D3DDevice device, ImagingFactory factory, BitmapDecoder bitmapDecoder) { if (bitmapDecoder.FrameCount == 0) { throw new ArgumentException("Image file successfully loaded, but it has no image frames."); } BitmapFrameDecode bitmapFrameDecode = bitmapDecoder.GetFrame(0); BitmapSource bitmapSource = bitmapFrameDecode.ToBitmapSource(); // create texture description Texture2DDescription textureDescription = new Texture2DDescription() { Width = bitmapSource.Size.Width, Height = bitmapSource.Size.Height, MipLevels = 1, ArraySize = 1, Format = Format.R8G8B8A8UNorm, SampleDescription = new SampleDescription() { Count = 1, Quality = 0, }, Usage = Usage.Dynamic, BindingOptions = BindingOptions.ShaderResource, CpuAccessOptions = CpuAccessOptions.Write, MiscellaneousResourceOptions = MiscellaneousResourceOptions.None }; // create texture Texture2D texture = device.CreateTexture2D(textureDescription); // Create a format converter FormatConverter converter = factory.CreateFormatConverter(); converter.Initialize( bitmapSource, PixelFormats.Prgba32Bpp, BitmapDitherType.None, BitmapPaletteType.Custom); // get bitmap data byte[] buffer = converter.CopyPixels(); // Copy bitmap data to texture MappedTexture2D texmap = texture.Map(0, Map.WriteDiscard, Microsoft.WindowsAPICodePack.DirectX.Direct3D10.MapOptions.None); Marshal.Copy(buffer, 0, texmap.Data, buffer.Length); texture.Unmap(0); // create shader resource view description ShaderResourceViewDescription srvDescription = new ShaderResourceViewDescription() { Format = textureDescription.Format, ViewDimension = ShaderResourceViewDimension.Texture2D, Texture2D = new Texture2DShaderResourceView() { MipLevels = textureDescription.MipLevels, MostDetailedMip = 0 } }; // create shader resource view from texture return(device.CreateShaderResourceView(texture, srvDescription)); }
private void CreateFactories() { //reuse factories except for random cases if (random.NextDouble() < 0.5) { lock (sharedSyncObject) { if (sharedD2DFactory == null) { // Create the D2D Factory sharedD2DFactory = D2DFactory.CreateFactory(D2DFactoryType.SingleThreaded); // Create the DWrite Factory sharedDwriteFactory = DWriteFactory.CreateFactory(); // Create the WIC Factory sharedWicFactory = ImagingFactory.Create(); Debug.Assert(sharedD2DFactory.NativeInterface != IntPtr.Zero); Debug.Assert(sharedDwriteFactory.NativeInterface != IntPtr.Zero); Debug.Assert(sharedWicFactory.NativeInterface != IntPtr.Zero); } sharedRefCount++; } d2DFactory = sharedD2DFactory; dwriteFactory = sharedDwriteFactory; wicFactory = sharedWicFactory; Debug.Assert(d2DFactory.NativeInterface != IntPtr.Zero); Debug.Assert(dwriteFactory.NativeInterface != IntPtr.Zero); Debug.Assert(wicFactory.NativeInterface != IntPtr.Zero); } else { // Create the D2D Factory d2DFactory = D2DFactory.CreateFactory(D2DFactoryType.Multithreaded); // Create the DWrite Factory dwriteFactory = DWriteFactory.CreateFactory(); // Create the WIC Factory wicFactory = ImagingFactory.Create(); Debug.Assert(d2DFactory.NativeInterface != IntPtr.Zero); Debug.Assert(dwriteFactory.NativeInterface != IntPtr.Zero); Debug.Assert(wicFactory.NativeInterface != IntPtr.Zero); } }
private void CreateFactories() { // Create the D2D Factory d2DFactory = D2DFactory.CreateFactory(D2DFactoryType.MultiThreaded); // Create the DWrite Factory dwriteFactory = DWriteFactory.CreateFactory(); // Create the WIC Factory wicFactory = new ImagingFactory(); Debug.Assert(d2DFactory.NativeInterface != IntPtr.Zero); Debug.Assert(dwriteFactory.NativeInterface != IntPtr.Zero); Debug.Assert(wicFactory.NativeInterface != IntPtr.Zero); }
/// <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 FrameBitmap(ImagingFactory factory, SharpDX.Direct2D1.Bitmap bitmap) : base(new D2DBitmapImpl(factory, bitmap)) { }