簡體   English   中英

C#Windows Phone-創建圓形蒙版

[英]C# Windows Phone - Creating a round mask

我需要遮蓋動態創建的圖像,以便將它們顯示為圓圈。 圖片可以是正方形,但通常是矩形...因此可以從圖片的中心截取要顯示的圓圈...因此,所顯示的圓圈必須刻在圖片中並居中居中。

這是我現在正在使用的代碼:

//Setting up the image
Image image = new Image();
image.Height = 70;
image.Width = 70;
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.UriSource = new Uri("http://url-of-the-image", UriKind.Absolute);
image.CacheMode = new BitmapCache();
image.Source = bitmapImage;
image.Stretch = Stretch.UniformToFill;
image.VerticalAlignment = System.Windows.VerticalAlignment.Center;

//Setting up the mask
RadialGradientBrush opacityMask = new RadialGradientBrush();
GradientStop gs1 = new GradientStop();
GradientStop gs2 = new GradientStop();
GradientStop gs3 = new GradientStop();
gs1.Color = Color.FromArgb(255, 0, 0, 0);
gs1.Offset = 0.0;
gs2.Color = Color.FromArgb(255, 0, 0, 0);
gs2.Offset = 0.999;
gs3.Color = Color.FromArgb(0, 0, 0, 0);
gs3.Offset = 1.0;
opacityMask.GradientStops.Add(gs1);
opacityMask.GradientStops.Add(gs2);
opacityMask.GradientStops.Add(gs3);
image.OpacityMask = opacityMask;

//Showing the image
panel.Children.Add(image);

這一切都很好,但是當圖片是矩形而不是正方形時,會創建一個橢圓而不是一個圓形...關於如何強制其創建一個圓形的任何想法?

我也嘗試指定更多參數,但似乎無濟於事:

opacityMask.Center = new Point(0.5, 0.5);
opacityMask.RadiusX = 0.5;
opacityMask.RadiusY = 0.5;

好的,今天我再次嘗試解決此問題,然后提出了解決方案。 這不是有史以來最好的,更干凈的解決方案...但是可以:)

我基本上將圖片(未遮罩)包裝到StackPanel中,然后將遮罩應用於StackPanel;)

這是這樣的樣子(與原始行唯一不同的是最后幾行):

//Setting up the image
Image image = new Image();
image.Height = 70;
image.Width = 70;
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.UriSource = new Uri("http://url-of-the-image", UriKind.Absolute);
image.CacheMode = new BitmapCache();
image.Source = bitmapImage;
image.Stretch = Stretch.UniformToFill;
image.VerticalAlignment = System.Windows.VerticalAlignment.Center;

//Setting up the mask
RadialGradientBrush opacityMask = new RadialGradientBrush();
GradientStop gs1 = new GradientStop();
GradientStop gs2 = new GradientStop();
GradientStop gs3 = new GradientStop();
gs1.Color = Color.FromArgb(255, 0, 0, 0);
gs1.Offset = 0.0;
gs2.Color = Color.FromArgb(255, 0, 0, 0);
gs2.Offset = 0.999;
gs3.Color = Color.FromArgb(0, 0, 0, 0);
gs3.Offset = 1.0;
opacityMask.GradientStops.Add(gs1);
opacityMask.GradientStops.Add(gs2);
opacityMask.GradientStops.Add(gs3);

//Setting up the StackPanel
StackPanel sp = new StackPanel();
sp.OpacityMask = opacityMask;

//Showing the image
sp.Children.Add(image);
panel.Children.Add(sp);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM