C#Windows Phone-创建一个圆形掩码

本文关键字:一个 掩码 Phone- 创建 C#Windows | 更新日期: 2023-09-27 18:26:44

我需要屏蔽动态创建的图像,这样它们就会显示为圆形。图片可以是正方形,但通常是矩形。。。所以将要显示的圆可以从它的中心截取…所以所显示的圆必须内切在图片中,并以图片的中心为中心。

这是我现在使用的代码:

//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;

C#Windows Phone-创建一个圆形掩码

好吧,今天我再次尝试解决这个问题,并提出了解决方案。这不是有史以来最好、更干净的解决方案。。。但有效:)

我基本上把图片(没有蒙版)包装到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);