wpf 实现 css3 中 boxshadow inset 效果

时间:2022-02-24 10:22:30
using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Shapes; public class BoxShadow {
public static Grid Create(Size size, Rect inner, GradientStopCollection sc) {
Func<PointCollection> ps = () => new PointCollection(Enumerable.Range(, ).Select(i => new Point()));
var left = new Polygon();
left.Points = ps();
left.Points[] = inner.TopLeft;
left.Points[] = inner.BottomLeft;
left.Points[] = new Point(, size.Height);
left.Fill = new LinearGradientBrush(sc, new Point(, ), new Point(, ));
var top = new Polygon();
top.Points = ps();
top.Points[] = new Point(size.Width, );
top.Points[] = inner.TopRight;
top.Points[] = inner.TopLeft;
top.Points[] = new Point(size.Width, );
top.Fill = new LinearGradientBrush(sc, new Point(, ), new Point(, ));
var right = new Polygon();
right.Points = ps();
right.Points[] = new Point(size.Width, size.Height);
right.Points[] = inner.BottomRight;
right.Points[] = inner.TopRight;
right.Points[] = new Point(size.Width, );
right.Points[] = new Point(size.Width, size.Height);
right.Fill = new LinearGradientBrush(sc, new Point(, ), new Point(, ));
var btm = new Polygon();
btm.Points = ps();
btm.Points[] = new Point(, size.Height);
btm.Points[] = inner.BottomLeft;
btm.Points[] = inner.BottomRight;
btm.Points[] = new Point(size.Width, size.Height);
btm.Points[] = new Point(, size.Height);
btm.Fill = new LinearGradientBrush(sc, new Point(, ), new Point(, )); var box = new Grid { Width = size.Width, Height = size.Height };
box.Children.Add(left);
box.Children.Add(top);
box.Children.Add(right);
box.Children.Add(btm);
return box;
}
}

wpf 实现 css3 中 boxshadow inset  效果

var sc = new GradientStopCollection();
foreach (var item in new Dictionary<double, Color> { { , white }, { ., black }, { ., white }, { ., black }, { ., white } }) {
sc.Add(new GradientStop { Offset = item.Key, Color = item.Value });
}
var box = BoxShadow.Create(new Size(, ), new Rect(, , , ), sc);
for (var i = ; i < ; i++) {
movingBlock.Children.Add(new Grid {
Width = movingBlock.Width / ,
Height = movingBlock.Width / ,
Background = new VisualBrush { Visual = box }
});

//调一调颜色和 box 的 Rotate,就会出现小星星!