码迷,mamicode.com
首页 > 其他好文 > 详细

给图片加上阴影效果

时间:2018-11-08 00:17:48      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:idt   stroke   font   windows   inf   ram   info   option   tst   

原文:给图片加上阴影效果

今天写一个小程序有一个给图片加上阴影的需求,记得WPF的Effect中就有阴影特效,就打算用它了。代码如下:

    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;

 

主要是如下几步:

  1. DrawingContext中绘图
  2. 通过DrawingVisualDrawingContext转换为Visual
  3. 通过RenderTargetBitmap将Visual转换为BitmapFrame
  4. 通过xxxBitmapEncoderBitmapFrame保存为图像

这些步骤也无需严格遵守,像我最开始的那个例子则是直接生成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);
    }

给图片加上阴影效果

标签:idt   stroke   font   windows   inf   ram   info   option   tst   

原文地址:https://www.cnblogs.com/lonelyxmas/p/9926345.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!