我从 Android 入手,从事图像处理方面的工作。 我想创建一个带有随机黑白像素的网格。我尝试使用位图,但我不太明白它是如何工作的。
我尝试使用以下代码,但它说: 表达式的类型必须是数组类型但它解析为 Matrix
即使没有这个错误,我也不确定这是继续进行的正确方法。所以如果你有任何想法......
谢谢!
import java.util.Random;
import android.support.v7.app.ActionBarActivity;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
public class MainActivity extends ActionBarActivity {
private ImageView img;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
img = (ImageView)findViewById(R.id.imageView1);
}
public void RandomImage (View view)
{
Random rand = new Random();
Matrix mat = new Matrix();
for (int i=0; i<100; i++)
{
for (int j=0; j<100 ; j++)
{
mat[i][j]=rand.nextInt(1);
img.setImageMatrix(mat);
}
}
}
}
最佳答案
您可以使用位图来实现这一点,首先创建一个具有首选大小(在本例中为 100*100)的位图:
int width = 100;
int height = 100;
Bitmap randomGridBitmap = Bitmap.createBitmap(width,height, Bitmap.Config.RGB_565);
用黑色或白色像素给这个位图着色(遍历每个像素并分配一个“随机颜色”):
Random rand = new Random();
for (int i=0; i<width; i++){
for (int j=0; j<height ; j++){
// default color : Black
int colorToPut = Color.BLACK;
// If lucky get a white pixel ;)
if(rand.nextInt(2)==0){
colorToPut = Color.WHITE;
}
// Set color to (i,j) pixel
randomGridBitmap.setPixel(i,j,colorToPut);
}
}
最后将此位图放入您的 ImageView 中:
imv.setImageBitmap(randomGridBitmap);
在全局范围内,您的 Activity 应如下所示:
public class MainActivity extends ActionBarActivity {
private ImageView img;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
img = (ImageView)findViewById(R.id.imageView1);
createAndSetRandomImage();
}
public void createAndSetRandomImage(){
Random rand = new Random();
for (int i=0; i<width; i++){
for (int j=0; j<height ; j++){
// default color : Black
int colorToPut = Color.BLACK;
// If lucky get a white pixel ;)
if(rand.nextInt(2)==0){
colorToPut = Color.WHITE;
}
// Set color to (i,j) pixel
randomGridBitmap.setPixel(i,j,colorToPut);
}
}
imv.setImageBitmap(randomGridBitmap);
}
}
你尝试使用setImageMatrix()方法(奇怪的是没有记录)但它用于转换 ImageView 的图像(例如旋转或自定义缩放图像)而不是设置图像。
关于java - Android 上的随机黑白网格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27063294/