【MAUI】模糊控件(毛玻璃高斯模糊亚克力模糊)
文章目录
- XAML
- .CS
- ToBytes方法
- 使用
- 效果
常试过AcrylicView.MAUI和Sharpnado.MaterialFrame,对于二者教程很少,使用直接写控件然后调属性,没有报错但也并没有效果所幸就自己写一个
XAML
<?xml version="1.0" encoding="utf-8" ?>
<ContentView xmlns="http://schemas.microsoft.com/dotnet/2021/maui"xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"x:Class="Namespace.BackgroundBlurView"xmlns:skia="clr-namespace:SkiaSharp.Views.Maui.Controls;assembly=SkiaSharp.Views.Maui.Controls"
><ContentView.Content><Grid RowDefinitions="*"><skia:SKCanvasView Grid.Row="0"x:Name="canvasView"HorizontalOptions="Fill"PaintSurface="OnCanvasViewPaintSurface"VerticalOptions="Fill" /></Grid></ContentView.Content>
</ContentView>
.CS
using CSharpFunctionalExtensions;
using SkiaSharp;
using SkiaSharp.Views.Maui;namespace Namespace ;public partial class BackgroundBlurView : ContentView
{#region 可绑定属性public static readonly BindableProperty PathProperty =BindableProperty.Create(propertyName: nameof(Path),returnType: typeof(string),declaringType: typeof(BackgroundBlurView),defaultBindingMode: BindingMode.OneWay,propertyChanged: PathPropertyChanged);public string Path{get { return (string)base.GetValue(PathProperty); }set { base.SetValue(PathProperty, value); }}private static void PathPropertyChanged(BindableObject bindable, object oldValue, object newValue){var control = (BackgroundBlurView)bindable;MainThread.BeginInvokeOnMainThread(() =>{control.canvasView.InvalidateSurface();});}#endregionbyte[] _musicbgBytes;public BackgroundBlurView(){InitializeComponent();}void OnCanvasViewPaintSurface(object sender, SKPaintSurfaceEventArgs args){SKImageInfo info = args.Info;SKSurface surface = args.Surface;SKCanvas canvas = surface.Canvas;canvas.Clear();float sigmaX = 20f;float sigmaY = 20f;using (SKPaint paint = new SKPaint()){// Set SKPaint propertiespaint.ImageFilter = SKImageFilter.CreateBlur(sigmaX, sigmaY);// Calculate rectangle for bitmapSKRect bitmapRect = new SKRect(0, 0, info.Width, info.Height);//bitmapRect.Inflate(-50, -50);using var stream = FileSystem.OpenAppPackageFileAsync("imgs/"+ Path).Result;_musicbgBytes = stream.ToBytes();if (_musicbgBytes==null){return;}SKBitmap bitmap = SKBitmap.Decode(_musicbgBytes);//SKBitmap.Decode("/Resources/Images/music/yinhe_bg.png");canvas.DrawBitmap(bitmap, bitmapRect, paint: paint);}}
}
ToBytes方法
public static byte[] ToBytes(this Stream stream)
{MemoryStream memoryStream = new MemoryStream();stream.CopyTo(memoryStream);return memoryStream.ToArray();
}
使用
<view:BackgroundBlurView VerticalOptions="Fill" HorizontalOptions="Fill" Padding="-10" Path="{Binding BGImg}"></view:BackgroundBlurView>