Unity-C#如何获取电脑桌面屏幕坐标像素对应的颜色RGB值

本文章包含屏幕坐标RGB采集器完整代码


前言

编写的脚本有时候需要获取屏幕坐标的RGB值,以便判断屏幕显示内容是否刷新,所以就需要一段获取屏幕RGB值的代码。


提示:以下是本篇文章正文内容,下面案例可供参考

一、完整代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Runtime.InteropServices;
using System;
using Color = System.Drawing.Color;

public class ColorManager : MonoBehaviour
{
    
    

    [DllImport("user32.dll")]
    static extern IntPtr GetDC(IntPtr hwnd);

    [DllImport("user32.dll")]
    static extern Int32 ReleaseDC(IntPtr hwnd, IntPtr hdc);

    [DllImport("gdi32.dll")]
    static extern uint GetPixel(IntPtr hdc, int nXPos, int nYPos);
    
    static public System.Drawing.Color GetPixelColor(int x, int y)
    {
    
    
        IntPtr hdc = GetDC(IntPtr.Zero);
        uint pixel = GetPixel(hdc, x, y);
        ReleaseDC(IntPtr.Zero, hdc);
        Color color = Color.FromArgb((int)(pixel & 0x000000FF),
                     (int)(pixel & 0x0000FF00) >> 8,
                     (int)(pixel & 0x00FF0000) >> 16);
        
        return color;
    }
    private void Start()
    {
    
    
          //x是屏幕的横坐标,y是屏幕的纵坐标  
          Debug.Log(GetPixelColor(1157, 234));     
    }
}

二、测试结果

执行GetPixelColor(x,y)函数,获得结果其中A为透明度,255表示完全不透明在这里插入图片描述

三、屏幕坐标系拓展

在这里插入图片描述

总结

复制代码即可使用,需要调用相关引用库

猜你喜欢

转载自blog.csdn.net/m0_53680210/article/details/126774510
今日推荐