C# 控件转截图

  • 概述(Overview)

  参考了网上的分享,感觉都不太理想:

    1.一个控件内如果包含多个子控件时没有考虑顺序问题;

    2.超出控件可显示区域时不能长截图,有滚动条会多余截取了滚动条。

  这篇文章旨在解决这2个问题,实现带滚动条时可以长截图,并且给出了在多个子控件的情况下如何控制截图顺序的代码。有用可以点个赞。引用本文章请注明出处,谢谢。

  ( Referring to the Share on the Internet, I feel that it is not ideal: 1. If there are multiple sub-controls in a control, the order is not considered; 2. When the display area of the control is exceeded, the screenshot cannot be long, and the scroll bar will be redundantly intercepted. This essay aims to solve  two problem by implementing long screenshots with scrollbars, and gives code on how to control the order of screenshots in the case of multiple child controls. If it's useful, you can like it. Please indicate the source for citing this article, thank you.)

代码(Code)

/// <summary>
/// 绘制整个控件以及子控件
/// </summary>
/// <param name="parentControl">窗口/控件</param>
/// <param name="bitmap">bit图片</param>
/// <returns></returns>
private static Bitmap DrawToBitmap(this Control parentControl, Bitmap bitmap = null)
{
    //获取整个界面的大小
    var w = parentControl.DisplayRectangle.Width;
    var h = parentControl.DisplayRectangle.Height;

    //长截图
    if (bitmap == null)
    {
        bitmap = parentControl.BackgroundImage == null ? new Bitmap(w, h) : new Bitmap(parentControl.BackgroundImage,w,h);
    }

    if (parentControl.HasChildren)
    {
        //绘制控件内容(逆序处理:图层从下开始往上叠取)
        for (int i = parentControl.Controls.Count - 1; i >= 0; i--)
        {
            var subControl = parentControl.Controls[i];
            //重新计算图片在bitmap上的位置
            var newLocation = new Point(subControl.Location.X - parentControl.DisplayRectangle.X, subControl.Location.Y - parentControl.DisplayRectangle.Y);
            using (Bitmap temp = new Bitmap(subControl.Width, subControl.Height))
            using (Graphics g = Graphics.FromImage(bitmap))
            {
                subControl.DrawToBitmap(temp, new Rectangle(new Point(0, 0), subControl.Size));
                //递归继续处理在子控件上的控件
                DrawToBitmap(subControl, temp);
                //最后绘制到底图上
                g.DrawImage(temp, new Rectangle(newLocation, subControl.Size));
            }
        }
    }

    return bitmap;
}

  • 5
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值