某些新聞:小米logo換新,程式設計師一行程式碼(border-radius:19px)實現,目前此行程式碼價值200萬
某程式設計師內心:所以還是因為我程式碼寫太少了,所以這200萬才沒有我的份嗎?
這事兒也成功的引起了本羊的注意,花點時間,我們也用WPF來實現一下,到底這超圓角有多好看?
先上效果圖:
經過一番瞭解,其實本質也就一條數學函式:|x|^n+|y|^n=1,上程式碼:
1 public class UIElementHelper 2 { 3 public static double GetSuperCornerRadius(FrameworkElement obj) 4 { 5 return (double)obj.GetValue(SuperCornerRadiusProperty); 6 } 7 8 public static void SetSuperCornerRadius(FrameworkElement obj, double value) 9 { 10 obj.SetValue(SuperCornerRadiusProperty, value); 11 } 12 13 public static readonly DependencyProperty SuperCornerRadiusProperty = 14 DependencyProperty.RegisterAttached("SuperCornerRadius", typeof(double), typeof(UIElementHelper), new PropertyMetadata(0.0, new PropertyChangedCallback((s, e) => 15 { 16 var n = (double)e.NewValue; 17 var el = s as FrameworkElement; 18 if (n == 0) 19 { 20 el.Clip = null; 21 } 22 else 23 { 24 UpdateClip(el); 25 if (!el.IsLoaded) 26 { 27 el.SizeChanged += OnSizeChanged; 28 } 29 } 30 }))); 31 32 private static void OnSizeChanged(object sender, SizeChangedEventArgs e) 33 { 34 UpdateClip(sender as FrameworkElement, false); 35 } 36 37 private static void UpdateClip(FrameworkElement el, bool updatePoints = true) 38 { 39 if (!updatePoints && el.Clip is StreamGeometry clip && !clip.IsFrozen) 40 { 41 // 42 } 43 else 44 { 45 clip = new StreamGeometry(); 46 var points = GetSuperCornerRadiusPoints(GetSuperCornerRadius(el)); 47 using(var context = clip.Open()) 48 { 49 context.BeginFigure(points[0], true, true); 50 context.PolyBezierTo(points, true, true);//根據座標點畫貝塞爾曲線 51 } 52 points.Clear(); 53 el.Clip = clip;//元素的剪下路徑 54 } 55 var group = new TransformGroup(); 56 group.Children.Add(new TranslateTransform(1, 1));//WPF以左上角為座標原點,所以這裡進行位移 57 var w = el.RenderSize.Width / 2; 58 group.Children.Add(new ScaleTransform(w, w));//放大 59 clip.Transform = group; 60 } 61 62 /// <summary> 63 /// 計算超圓角路徑的座標點 64 /// </summary> 65 /// <param name="n"></param> 66 /// <returns></returns> 67 public static List<Point> GetSuperCornerRadiusPoints(double n = 3) 68 { 69 var points = new List<Point>(); 70 //求出Y>0時座標 71 for (double x = -1; x <= 1; x += 0.001) 72 { 73 var y = Math.Pow(1 - Math.Pow(Math.Abs(x), n), 1 / n);//公式:|x|^n+|y|^n=1 74 points.Add(new Point(x, Math.Round(y, 3)));//3位小數,精度應該足夠了 75 } 76 //Y<0的座標 77 var count = points.Count; 78 for (int i = 1; i < count + 1; i++) 79 { 80 var p = points[count - i]; 81 points.Add(new Point(p.X, p.Y * -1)); 82 } 83 return points; 84 } 85 86 87 }
工程檔案,感興趣的下載玩玩。