0

我需要屏蔽动态创建的图像,以便它们显示为圆圈。图片可以是正方形,但通常是矩形...所以要显示的圆圈可以从它的中心取出...所以显示的圆圈必须内接在图片中并以中心为中心。

这是我现在正在使用的代码:

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

1 回答 1

0

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

我基本上将图片(未蒙版)包装到 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);
于 2013-08-08T00:05:53.787 回答