如何在图形中获得像素颜色? [英] How to get pixel color in graphics?

查看:47
本文介绍了如何在图形中获得像素颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发了



I made

private void FormMario_Shown(object sender, EventArgs e)
        {
            g = CreateGraphics();
        }





然后我想要:



g .getPixel(x,y);



怎么办?



and then I want:

g.getPixel(x,y);

how to do that?

推荐答案

这不是可以从Graphics对象本身。但是,如果Graphics绑定到Bitmap,您可以使用Bitmap的 GetPixel 方法:

This isn't possible from the Graphics object itself. However, if the Graphics is bound to a Bitmap, you can use the GetPixel method of the Bitmap:
Color c = bmp.GetPixel(x, y);


我在某个地方找到了这个,所以我使用了窗体的对象作为控件



I found this somewhere so I used the object of the form as control

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;


namespace OSOL_NAMESPACE
{
    class ClassSetGetPixel
    {


        [DllImport("user32.dll")]
        static extern IntPtr GetDC(IntPtr hWnd);
        [DllImport("user32.dll")]
        static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC);
        [DllImport("gdi32.dll")]
        static extern int GetPixel(IntPtr hDC, int x, int y);
        [DllImport("gdi32.dll")]
        static extern int SetPixel(IntPtr hDC, int x, int y, int color);

        static public Color GetPixel(Control control, int x, int y)
        {
            Color color = Color.Empty;
            if (control != null)
            {
                IntPtr hDC = GetDC(control.Handle);
                int colorRef = GetPixel(hDC, x, y);
                color = Color.FromArgb(
                    (int)(colorRef & 0x000000FF),
                    (int)(colorRef & 0x0000FF00) >> 8,
                    (int)(colorRef & 0x00FF0000) >> 16);
                ReleaseDC(control.Handle, hDC);
            }
            return color;
        }
        static public void SetPixel(Control control, int x, int y, Color color)
        {
            if (control != null)
            {
                IntPtr hDC = GetDC(control.Handle);
                int argb = color.ToArgb();
                int colorRef =
                    (int)((argb & 0x00FF0000) >> 16) |
                    (int)(argb & 0x0000FF00) |
                    (int)((argb & 0x000000FF) << 16);
                SetPixel(hDC, x, y, colorRef);
                ReleaseDC(control.Handle, hDC);
            }
        }


    }
}


这篇关于如何在图形中获得像素颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆