简体   繁体   中英

Bitmap.MakeTransparent for Windows Store App?

In Winforms we have a Bitmap.MakeTransparent method to set a color to be transparent. Is there an equivalent method in UWP? (For WriteableBitmap or SoftwareBitmap etc.)

There are several ways to approach this:

First, if you are using the bitmap as a UI control's imagebrush, You can just set its Opacity per your requirement. A simple demo is like below:

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
   <Rectangle x:Name="rct" Width="800" Height="800">
      <Rectangle.Fill>
       <ImageBrush x:Name="ib" ImageSource="Assets//hero.bmp" Stretch="Uniform" Opacity="0.5"/>
      </Rectangle.Fill>
   </Rectangle>
</Grid>

Second way is to use Windows Imaging Component. Here you can find sample about using Direct2D and WIC Image together. Below are two simple solutions:

1) Using the IWICFormatConverter interface.

In IWICFormatConverter.Initialize() set Alpha threshold per your requirement: The AlphaThreshold value is used to determine what level of opacity will be mapped to the fully transparent color in the converted format. A value of 9.8 implies that any pixel with an alpha value of less than 25 will be mapped to the transparent color. A value of 100 maps all pixels which are not fully opaque to the transparent color. Then you can draw bitmap by D2D.

 hr = m_pConvertedSourceBitmap->Initialize(
           pFrame,                          // Input bitmap to convert
           GUID_WICPixelFormat32bppPBGRA,   // Destination pixel format
           WICBitmapDitherTypeNone,         // Specified dither pattern
           NULL,                            // Specify a particular palette 
           0.f,                             // Alpha threshold
           WICBitmapPaletteTypeCustom       // Palette translation type
           );

2) Obtain an IWICBitmapLock for a specified rectangle of the IWICBitmap, then process the pixel data that is now locked by the IWICBitmapLock object.

Of course there are other solutions, such as Using a WriteableBitmap to manipulate image pixels directly. Here is a sample to access pixels with the help of PixelDataProvider class to access pixels in bitmap.

However, except the XAML UI element, there is yet no simple replacement for Bitmap.MakeTransparent. So it all depends on your usage model.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM