C#控件自定义形状(透明/镂空)

  • 概述(Overview)

    在网上搜了很多,都不太满意,找ChatGPT一问,效率慢,内存占用大,但是可以用:

      1.图片是什么形状,控件就是什么形状;

      2.穿透多层控件实现路径外的全透明/镂空。

    (I searched a lot on the Internet, but I was not satisfied, and I asked ChatGPT, which was slow and had a large memory, but it could be used: 1. What is the shape of the picture, what shape is the control; 2. Penetrate multi-layer controls to achieve full transparency/hollowing out of the path.)

  • 获取控件的Region(Code)

  • /// <summary>
    /// 根据图片计算Region路径(低效率——更高效率请使用指针/内存法处理,引用之处有具体的代码,可自行点击跳转查看)
    /// </summary>
    /// <param name="image">图像资源</param>
    public Region ImageToRegion(Image image)
    {
        if (image == null)
        {
            return null;
        }
     
        GraphicsPath path = new GraphicsPath();
     
        Bitmap bitmap = new Bitmap(image);
        // 扫描图片的每个像素,将不透明部分添加到GraphicsPath中
        for (int x = 0; x < bitmap.Width; x++)
        {
            for (int y = 0; y < bitmap.Height; y++)
            {
                if (bitmap.GetPixel(x, y).A > 0) // 如果像素不透明
                {
                    // 将像素坐标添加到GraphicsPath中
                    path.AddRectangle(new Rectangle(x, y, 1, 1));
                }
            }
        }
        bitmap.Dispose();
     
        return new Region(path);
    }  
  • 处理控件的Region(Code)

    public SharpControl()
    {
        InitializeComponent();
        //图片是什么形状,控件就是什么形状
        this.Region = ImageToRegion(this.BackgroundImage);
    }
    
  • 引用(Reference)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值