You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何识别UI纹理一维颜色数组中的边缘像素

Fixing Edge Detection for UI Texture Outline in 1D Color Array

I see the issue with your original code—your right edge calculation was using the wrong modulus operation, which is why it wasn't correctly identifying those pixels. Let's break down what went wrong and how the corrected approach fixes it.

The Problem in Your Original Code

Your right edge check p % height == height - outlineWidth is incorrect because:

  • The 1D index p maps to 2D coordinates (x, y) where x = p % width (horizontal position) and y = p / width (vertical position, using integer division)
  • To detect the right edge, you need to check the x-coordinate (not y-coordinate/height) being in the last outlineWidth columns of the row, not using modulus with height.

Corrected Implementation

Instead of cramming all edge checks into a single loop (which leads to easy-to-miss logic errors), the revised approach separates each edge into its own explicit loop. This makes the code clearer and far less prone to bugs:

// Initialize array and fill all pixels with base color first
Color[] colorData = new Color[width * height];
for (int p = 0; p < colorData.Length; p++)
{
    colorData[p] = DefaultBaseColor;
}

// Top edge: overwrite first N rows (N = outlineWidth)
for (int p = 0; p < width * outlineWidth; p++)
{
    colorData[p] = DefaultOutlineColor;
}

// Left and right edges: iterate through each row, set edge columns
for (int y = 1; y < height; y++)
{
    for (int i = 0; i < outlineWidth; i++)
    {
        // Left edge: x = i in current row y
        colorData[y * width + i] = DefaultOutlineColor;
        // Right edge: x = width - 1 - i in current row y
        colorData[y * width + (width - 1 - i)] = DefaultOutlineColor;
    }
}

// Bottom edge: overwrite last N rows (N = outlineWidth)
for (int p = width * (height - outlineWidth); p < colorData.Length; p++)
{
    colorData[p] = DefaultOutlineColor;
}

Why This Works

  1. Base Color First: We start by filling the entire array with the base color, so we only need to overwrite the edge pixels afterward—no complicated conditional checks for every single pixel.
  2. Top/Bottom Edges: These use simple index ranges to target the first and last outlineWidth rows, which is intuitive and hard to mess up.
  3. Left/Right Edges: For each row (skipping the top/bottom which are already handled), we explicitly set the first outlineWidth columns (left edge) and last outlineWidth columns (right edge) using proper 2D-to-1D index conversion (y * width + x).

This approach works reliably for any outlineWidth value, not just single-pixel edges, and is much easier to debug or modify later.

内容的提问来源于stack exchange,提问作者Spool

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:06:20