如何识别UI纹理一维颜色数组中的边缘像素
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
pmaps to 2D coordinates(x, y)wherex = p % width(horizontal position) andy = 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
outlineWidthcolumns 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
- 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.
- Top/Bottom Edges: These use simple index ranges to target the first and last
outlineWidthrows, which is intuitive and hard to mess up. - Left/Right Edges: For each row (skipping the top/bottom which are already handled), we explicitly set the first
outlineWidthcolumns (left edge) and lastoutlineWidthcolumns (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

