java - 检测光标附近区域内的颜色

标签 java

我希望能够检测鼠标指针附近的正方形或圆形区域(以更容易的为准)内的颜色。我下面的示例有效,但鼠标必须直接放在颜色上才能检测到它。 在我的示例中,我只是使用了 MS Paint 标准红色,但我希望检测渐变区域中的特定颜色,当我的光标位于目标颜色的上方、下方、左侧或右侧 100 个像素时,它将检测到它。我想我需要在光标当前位置周围的像素范围内循环,但我似乎无法得到它。 添加到我的代码确实会有所帮助,因为我已经在这个网站和其他人尝试想法上花费了太多时间。

谢谢!

import java.awt.Color;

import java.awt.MouseInfo;

import java.awt.Point;

import java.awt.PointerInfo;

import java.awt.Robot;

public class DetectRed {

public static void main(String[] args) throws Exception {

PointerInfo pointer;

pointer = MouseInfo.getPointerInfo();

Point coord = pointer.getLocation();

        Robot robot = new Robot();
        robot.delay(2000);

        while(true)
        {
            //print coords
            coord = MouseInfo.getPointerInfo().getLocation();
            System.out.println("Coord = " + coord);

            //print colors
            Color color = robot.getPixelColor((int)coord.getX(), (int)coord.getY());
            System.out.println("Color = " + color);

            if(color.getRed() == 237 && color.getGreen() == 28 && color.getBlue() == 36)
            {
                System.out.println("RED(237,28,36) FOUND");
            }

            System.out.println(); //blank line separator

            robot.delay(500); //use shorter delay to scan faster...
        }
    }
}

最佳答案

将颜色检测包装在 for 循环中以扫描邻域:

for (int x = (int)coord.getX()-window; x <= (int)coord.getX()+window; ++x) {
  for (int y = (int)coord.getY()-window; y <= (int)coord.getY()+window; ++y) {
    Color color = robot.getPixelColor(x, y);
    // Check if it matches.
  }
}

您可能需要进行一些边界检查,以确保 x-windowx+window(对于 y 也类似)位于矩形的边界内。当然,请根据您的特定要求选择窗口

关于java - 检测光标附近区域内的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28565728/

相关文章:

java - 通过java程序从Hibernate.cfg.xml中获取DataBase名称

java - 具有代码覆盖率的 REST API 集成测试

java - 理解 Spring beans 标签声明

Java - SimpleDateFormat 意外的解析行为

带有表盘外观的 Java slider

java - 根据总值(value)对值组进行排序

java - 为什么时间序列集合图表中的数据显示不正确?

java.lang.OutOfMemory错误: GC overhead limit exceeded android studio

java - 连接丢失后自动重新连接 JPA EntityManager

java.net.MalformedURLException : no protocol:/intl/en/policies/GET Request