首页 > 代码库 > wpf 实现 css3 中 boxshadow inset 效果

wpf 实现 css3 中 boxshadow inset 效果

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(0, 5).Select(i => new Point()));
        var left = new Polygon();
        left.Points = ps();
        left.Points[1] = inner.TopLeft;
        left.Points[2] = inner.BottomLeft;
        left.Points[3] = new Point(0, size.Height);
        left.Fill = new LinearGradientBrush(sc, new Point(0, 0), new Point(1, 0));
        var top = new Polygon();
        top.Points = ps();
        top.Points[0] = new Point(size.Width, 0);
        top.Points[1] = inner.TopRight;
        top.Points[2] = inner.TopLeft;
        top.Points[4] = new Point(size.Width, 0);
        top.Fill = new LinearGradientBrush(sc, new Point(0, 0), new Point(0, 1));
        var right = new Polygon();
        right.Points = ps();
        right.Points[0] = new Point(size.Width, size.Height);
        right.Points[1] = inner.BottomRight;
        right.Points[2] = inner.TopRight;
        right.Points[3] = new Point(size.Width, 0);
        right.Points[4] = new Point(size.Width, size.Height);
        right.Fill = new LinearGradientBrush(sc, new Point(1, 0), new Point(0, 0));
        var btm = new Polygon();
        btm.Points = ps();
        btm.Points[0] = new Point(0, size.Height);
        btm.Points[1] = inner.BottomLeft;
        btm.Points[2] = inner.BottomRight;
        btm.Points[3] = new Point(size.Width, size.Height);
        btm.Points[4] = new Point(0, size.Height);
        btm.Fill = new LinearGradientBrush(sc, new Point(0, 1), new Point(0, 0));

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

技术分享

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

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

wpf 实现 css3 中 boxshadow inset 效果