2 回答

TA貢獻1820條經驗 獲得超2個贊
我建議將其分解為較小的問題并單獨處理。首先只關注一個案例,也許是最簡單的一個,然后再解決其他案例。
就在我的腦海里,別讓我太在意數學……
public static int stripesColor(int column, int row, int imWidth, int imHeight) {
// Just worry about the square in the center for now.
// If pixel is not in left/bottom or top/right quarters:
if (imWidth / 4 < column < (imWidth * 3)/4) &&
(imHeight / 4 < row < (imHeight * 3)/4) {
return Color.hotpink.getRGB();
} else if {
// We know that any pixel in the center square is already taken care of,
// so the logic for the rest can completely ignore that.
// It can be written as though the square isn't in the image at all.
} else {
// Last remaining color
}
}
我也不知道內部正方形的暗淡是總大小的 1/2 還是 3/5;我在這里假設為 1/2,但最終這并不重要。希望這可以幫助您擺脫困境。
如果條件內的數學if看起來很糟糕,您始終可以為這些值初始化單獨的變量,然后條件將更加清晰(并且基本上是自記錄的)。

TA貢獻1841條經驗 獲得超3個贊
這與其說是一個編碼問題,不如說是一個如何構建組合邏輯的問題。
讓我們拆開盒子。該盒子基本上由三部分組成 - 左上半部分的黃色三角形,右下半部分的青色三角形,以及覆蓋在頂部的洋紅色正方形。
好的。讓我們看第一部分——我們如何定義圖像的左上半部分?如果我們將方形圖像像素視為圖形,則分割黃色和青色的中心線就是從原點 (0,0) 到左上角 (imWidth, imHeight) 的線。這條線的斜率為 1,形式為 y=x。因此,左上角的像素是列 <= 行的任何位置。
因此,當column <= row時,我們將返回值設置為黃色整數值。
對于左下角,我們選擇相反的比較,因此當列 > 行時,我們將返回值設置為青色整數值。
現在為了處理覆蓋,我們想要找到像素位于該中心區域內的情況。假設我們希望圖像占據中間的 80%,那么我們需要將緩沖區設置為總大小的 10%。所以我們檢查的是是否 (imWidth * (0.1) < row ) && (row < imWidth * (1-0.1)) && (imHeight * (0.1) < column) && (column < imHeight * (1-0.1) ))
public static int boxColor(int column, int row, int imWidth, int imHeight) {
final int UPPER_LEFT_COLOR = 0; // Set to upper-left color.
final int LOWER_RIGHT_COLOR = 128; // Set to lower-right color.
final int CENTER_SQUARE_COLOR = 255; // Set to center color.
final double MARGIN_AMOUNT = 0.1; // Set to buffer percentage
int return_color = 0; //Initialize the return value to something.
// First set the return value based on the midline split.
if (column <= row) {
return_color = UPPER_LEFT_COLOR;
} else {
return_color = LOWER_RIGHT_COLOR;
}
// Test for the overlay and reset the return value.
if ((imWidth * (MARGIN_AMOUNT) < row ) && (row < imWidth * (1-MARGIN_AMOUNT)) && (imHeight * (MARGIN_AMOUNT) < column) && (column < imHeight * (1-MARGIN_AMOUNT))) {
return_color = CENTER_SQUARE_COLOR;
}
// Return the finally determined value.
return return_color;
}
添加回答
舉報