gpt4 book ai didi

java - 绘图 Canvas 上的二维数组网格

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:33:03 27 4
gpt4 key购买 nike

我正在编写一个像素艺术应用程序,将用户在屏幕上绘制的图像绘制成像素外观。有两种方法可以接近它。要么在保存后对图像进行像素化,要么在手边设置网格,以便用户绘制像素图像。我在后面的方法中找不到任何东西。所以我的第一个问题是绘制一个网格,如果一个单元格被触摸我会改变它的颜色。我尝试在 Canvas 上绘制矩形,但这毫无意义,因为我无法控制单元格。

我在考虑在每个单元格创建位图的嵌套 for 循环?

最佳答案

以下只是一个简单的示例。它没有优化,没有实现异常处理等。

public class PixelGridView extends View {
private int numColumns, numRows;
private int cellWidth, cellHeight;
private Paint blackPaint = new Paint();
private boolean[][] cellChecked;

public PixelGridView(Context context) {
this(context, null);
}

public PixelGridView(Context context, AttributeSet attrs) {
super(context, attrs);
blackPaint.setStyle(Paint.Style.FILL_AND_STROKE);
}

public void setNumColumns(int numColumns) {
this.numColumns = numColumns;
calculateDimensions();
}

public int getNumColumns() {
return numColumns;
}

public void setNumRows(int numRows) {
this.numRows = numRows;
calculateDimensions();
}

public int getNumRows() {
return numRows;
}

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
calculateDimensions();
}

private void calculateDimensions() {
if (numColumns < 1 || numRows < 1) {
return;
}

cellWidth = getWidth() / numColumns;
cellHeight = getHeight() / numRows;

cellChecked = new boolean[numColumns][numRows];

invalidate();
}

@Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.WHITE);

if (numColumns == 0 || numRows == 0) {
return;
}

int width = getWidth();
int height = getHeight();

for (int i = 0; i < numColumns; i++) {
for (int j = 0; j < numRows; j++) {
if (cellChecked[i][j]) {

canvas.drawRect(i * cellWidth, j * cellHeight,
(i + 1) * cellWidth, (j + 1) * cellHeight,
blackPaint);
}
}
}

for (int i = 1; i < numColumns; i++) {
canvas.drawLine(i * cellWidth, 0, i * cellWidth, height, blackPaint);
}

for (int i = 1; i < numRows; i++) {
canvas.drawLine(0, i * cellHeight, width, i * cellHeight, blackPaint);
}
}

@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
int column = (int)(event.getX() / cellWidth);
int row = (int)(event.getY() / cellHeight);

cellChecked[column][row] = !cellChecked[column][row];
invalidate();
}

return true;
}
}

这里有一个简单的 Activity 用于演示:

public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

PixelGridView pixelGrid = new PixelGridView(this);
pixelGrid.setNumColumns(4);
pixelGrid.setNumRows(6);

setContentView(pixelGrid);
}
}

关于java - 绘图 Canvas 上的二维数组网格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24842550/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com