温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C#如何使用Effects给图片增加阴影效果

发布时间:2022-06-18 13:54:50 来源:亿速云 阅读:132 作者:iii 栏目:开发技术

这篇文章主要讲解了“C#如何使用Effects给图片增加阴影效果”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“C#如何使用Effects给图片增加阴影效果”吧!

代码如下:

    using (var imageStreamSource = File.OpenRead(@"r:\4.png"))
    using (Stream fs = File.Create(@"r:\test.png"))
    {
        var decoder = BitmapDecoder.Create(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
        var bitmapFrame = decoder.Frames[0];

        var size = new Size(bitmapFrame.PixelWidth, bitmapFrame.PixelHeight);
        var img = new Image() { Source = bitmapFrame };
        img.Effect = new System.Windows.Media.Effects.DropShadowEffect();
        img.Arrange(new Rect(0,0,bitmapFrame.PixelWidth,bitmapFrame.PixelHeight));

        var rtb = new RenderTargetBitmap(bitmapFrame.PixelWidth, bitmapFrame.PixelHeight, 96, 96, PixelFormats.Pbgra32);
        rtb.Render(img);
        var png = new PngBitmapEncoder();
        png.Frames.Add(BitmapFrame.Create(rtb));
        png.Save(fs);
    }

使用过程中,发现WPF和GDI的处理方式还是有有些类似的。它的基本使用方式如下:

    Image myImage = new Image();
    FormattedText text = new FormattedText("ABC",
            new CultureInfo("en-us"),
            FlowDirection.LeftToRight,
            new Typeface(this.FontFamily, FontStyles.Normal, FontWeights.Normal, new FontStretch()),
            this.FontSize,
            this.Foreground);

    DrawingVisual drawingVisual = new DrawingVisual();
    DrawingContext drawingContext = drawingVisual.RenderOpen();
    drawingContext.DrawText(text, new Point(2, 2));
    drawingContext.Close();

    RenderTargetBitmap bmp = new RenderTargetBitmap(180, 180, 120, 96, PixelFormats.Pbgra32);
    bmp.Render(drawingVisual);
    myImage.Source = bmp;

主要是如下几步:

  • 在DrawingContext中绘图

  • 通过DrawingVisual将DrawingContext转换为Visual

  • 通过RenderTargetBitmap将Visual转换为BitmapFrame

  • 通过xxxBitmapEncoder将BitmapFrame保存为图像

这些步骤也无需严格遵守,像我最开始的那个例子则是直接生成Visual,然后保存为图像。其实我更喜欢这种方式,因为Visual是可以直接在WPF的界面上显示出来的,方便调试,并且很方便应用WPF中的各种特效。不过要记得调用一下Arrange函数,否则看不到生成结果的。

这里再给个更简单的例子,以供学习。

    Ellipse cir = new Ellipse();
    cir.Height = 50;
    cir.Width = 50;
    cir.Stroke = Brushes.Black;
    cir.StrokeThickness = 1.0;
    cir.Arrange(new Rect(new Size(50, 50)));    //这句不能漏了

    RenderTargetBitmap rtb = new RenderTargetBitmap(200, 200, 96, 96, PixelFormats.Pbgra32);
    rtb.Render(cir);

    PngBitmapEncoder png = new PngBitmapEncoder();
    png.Frames.Add(BitmapFrame.Create(rtb));
    using (Stream fs = File.Create(@"r:\test.png"))
    {
        png.Save(fs);
    }

感谢各位的阅读,以上就是“C#如何使用Effects给图片增加阴影效果”的内容了,经过本文的学习后,相信大家对C#如何使用Effects给图片增加阴影效果这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI