I want to draw a tile map on a canvas with drawRect() method. The problem is that it only draws the first rectangle on coordinate 0,0. It's suppose to be a 30x20 tile map of the colors red and green. I'm planning to make a snake game.
Tile.java
public class Tile extends View{
private final int TILE_SIZE = 16;
private static int[][] tileMap;
private static int rows, columns;
public Tile(Context context) {
super(context);
createTilemap();
}
public void createTilemap(){
tileMap = new int[30][20];
rows = tileMap.length;
columns = tileMap[1].length;
Random r = new Random();
for (int i = 0; i < rows; i++){
for (int j = 0; j < columns; j++){
tileMap[i][j] = r.nextInt(2);
}
}
}
public Tile(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint p = new Paint();
for (int i = 0; i < rows; i++){
for (int j = 0; j < columns; j++){
int pos_i = TILE_SIZE * i;
int pos_j = TILE_SIZE * j;
switch (tileMap[i][j]){
case 0:
p.setColor(Color.GREEN);
canvas.drawRect(pos_i, pos_j, TILE_SIZE, TILE_SIZE, p);
break;
case 1:
p.setColor(Color.RED);
canvas.drawRect(pos_i, pos_j, TILE_SIZE, TILE_SIZE, p);
break;
}
}
}
}
}
activity_main.xml
<com.example.mohamed.snake.Tile
android:layout_width="match_parent"
android:layout_height="match_parent" />
drawRect(left, top, right, bottom) will draw from left to right, from top to bottom. It will not draw if the difference is 0 or negative.
You're drawing from..
0 to TILE_SIZE,
TILE_SIZE to TILE_SIZE (width / height == 0)
2 * TILE_SIZE to TILE_SIZE (width / height actually becoming negative)
...and so on
You should use
canvas.drawRect(pos_i, pos_j, pos_i + TILE_SIZE, pos_j + TILE_SIZE, p);
to get the coordinates correct.
Your problem is in your 2nd for loop. Looks like a copy and paste error. In both createTilemap and onDraw, change:
for (int j = 0; i < columns; i++)
to:
for (int j = 0; j < columns; j++)
Also, your arguments to drawRect are wrong. They should be left,top,right,bottom not left,top,width,height. Try changing your code to this:
canvas.drawRect(pos_i, pos_j, pos_i + TILE_SIZE, pos_j + TILE_SIZE, p);
Related
I am currently working on zip animation to unlock android mobile screen. Changing background images is a expensive task and have not a smooth effect. I want a smooth effect in it. Any help please? Thanks
Try this:
The smooth effect makes use of Convolution Matrix:
Some image effects are better to implement using Convolution Matrix
method like: Gaussian Blur, Sharpening, Embossing, Smooth…
Check That Link to know more about Convolution Matrix or Another one
To do Convolution Matrix
import android.graphics.Bitmap;
import android.graphics.Color;
public class ConvolutionMatrix
{
public static final int SIZE = 3;
public double[][] Matrix;
public double Factor = 1;
public double Offset = 1;
public ConvolutionMatrix(int size) {
Matrix = new double[size][size];
}
public void setAll(double value) {
for (int x = 0; x < SIZE; ++x) {
for (int y = 0; y < SIZE; ++y) {
Matrix[x][y] = value;
}
}
}
public void applyConfig(double[][] config) {
for(int x = 0; x < SIZE; ++x) {
for(int y = 0; y < SIZE; ++y) {
Matrix[x][y] = config[x][y];
}
}
}
public static Bitmap computeConvolution3x3(Bitmap src, ConvolutionMatrix matrix) {
int width = src.getWidth();
int height = src.getHeight();
Bitmap result = Bitmap.createBitmap(width, height, src.getConfig());
int A, R, G, B;
int sumR, sumG, sumB;
int[][] pixels = new int[SIZE][SIZE];
for(int y = 0; y < height - 2; ++y) {
for(int x = 0; x < width - 2; ++x) {
// get pixel matrix
for(int i = 0; i < SIZE; ++i) {
for(int j = 0; j < SIZE; ++j) {
pixels[i][j] = src.getPixel(x + i, y + j);
}
}
// get alpha of center pixel
A = Color.alpha(pixels[1][1]);
// init color sum
sumR = sumG = sumB = 0;
// get sum of RGB on matrix
for(int i = 0; i < SIZE; ++i) {
for(int j = 0; j < SIZE; ++j) {
sumR += (Color.red(pixels[i][j]) * matrix.Matrix[i][j]);
sumG += (Color.green(pixels[i][j]) * matrix.Matrix[i][j]);
sumB += (Color.blue(pixels[i][j]) * matrix.Matrix[i][j]);
}
}
// get final Red
R = (int)(sumR / matrix.Factor + matrix.Offset);
if(R < 0) { R = 0; }
else if(R > 255) { R = 255; }
// get final Green
G = (int)(sumG / matrix.Factor + matrix.Offset);
if(G < 0) { G = 0; }
else if(G > 255) { G = 255; }
// get final Blue
B = (int)(sumB / matrix.Factor + matrix.Offset);
if(B < 0) { B = 0; }
else if(B > 255) { B = 255; }
// apply new pixel
result.setPixel(x + 1, y + 1, Color.argb(A, R, G, B));
}
}
// final image
return result;
}
}
Then to do Smooth effect
public static Bitmap smooth(Bitmap src, double value) {
ConvolutionMatrix convMatrix = new ConvolutionMatrix(3);
convMatrix.setAll(1);
convMatrix.Matrix[1][1] = value;
convMatrix.Factor = value + 8;
convMatrix.Offset = 1;
return ConvolutionMatrix.computeConvolution3x3(src, convMatrix);
}
You can change values and get the smooth effect as you want.
That tutorial it's found HERE
I am working in an android application to draw a circle and divide them equally and bind text inside the divided portion in the circle(like pichart). I have drawn a circle and divided them equally, but I want to bind text inside the divided portion. Please look into my code and give a solution. Thanks in advance.
public class MainActivity extends Activity {
/** Called when the activity is first created. */
float values[] = { 130, 130, 130, 130, 130 };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout linear = (LinearLayout) findViewById(R.id.linearlay);
values = calculateData(values);
linear.addView(new MyGraphview(this, values));
}
private float[] calculateData(float[] data) {
float total = 0;
for (int i = 0; i < data.length; i++) {
total += data[i];
}
for (int i = 0; i < data.length; i++) {
data[i] = 360 * (data[i] / total);
}
return data;
}
public class MyGraphview extends View {
private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
private float[] value_degree;
private int[] COLORS = { Color.YELLOW, Color.GREEN, Color.WHITE,
Color.CYAN, Color.RED };
RectF rectf = new RectF(10, 10, 300, 300);
Rect rect = new Rect(10, 10, 300, 300);
int temp = 0;
String rotatedtext;
Path path;
public MyGraphview(Context context, float[] values) {
super(context);
path = new Path();
value_degree = new float[values.length];
for (int i = 0; i < values.length; i++) {
value_degree[i] = values[i];
}
paint.setTextSize(16);
rotatedtext = "Rotated :)";
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
for (int i = 0; i < value_degree.length; i++) {
if (i == 0) {
paint.setColor(COLORS[i]);
canvas.drawArc(rectf, 0, value_degree[i], true, paint);
} else {
temp += (int) value_degree[i - 1];
paint.setColor(COLORS[i]);
canvas.drawArc(rectf, temp, value_degree[i], true, paint); //
}
}
}
}
}
Try this:
private String[] STRINGS = { "Yellow", "GREEN", "WHITE", "CYAN", "RED" }; // Array of strings, just for the sample
#Override
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
temp = 0;
int centerX = (rect.left + rect.right) / 2;
int centerY = (rect.top + rect.bottom) / 2;
int radius = (rect.right - rect.left) / 2;
radius *= 0.5; // 1 will put the text in the border, 0 will put the text in the center. Play with this to set the distance of your text.
for (int i = 0; i < data.length; i++)
{
if (i > 0)
temp += (int) data[i - 1]; // rewrote your code here a bit, to avoid duplicate code.
paint.setColor(COLORS[i]);
canvas.drawArc(rectf, temp, data[i], true, paint);
paint.setColor(Color.BLACK); // set this to the text color.
float medianAngle = (temp + (data[i] / 2f)) * (float)Math.PI / 180f; // this angle will place the text in the center of the arc.
canvas.drawText(STRINGS[i], (float)(centerX + (radius * Math.cos(medianAngle))), (float)(centerY + (radius * Math.sin(medianAngle))), paint);
}
}
Also, for nicer results, make sure to set the Align.CENTER property in the paint before drawing any text:
paint.setTextSize(16);
paint.setTextAlign(Align.CENTER);
Hope this helps :)
I've searched for how to pixelate an image in android via code, the results are varied.
I've found libraries and tutorials on how to apply other effects found here: http://xjaphx.wordpress.com/learning/tutorials/
Can someone clear things up for me, what is the simplest way of pixelating an image on the fly in android
Also it would be handy if it was a function that I could how many rounds or how much I wanted the image pixelating.
Thank in advance.
The simplest way to pixelate the image would be to scale image down using "nearest neighbour" algorithm, and then scale up, using the same algorithm.
Filtering over the image trying to find an average takes much more time, but does not actually give any improvements in result quality, after all you do intentionally want your image distorted.
I have done this before in vb.net and its easily made into a function whose parameter can control how pixelated you want it.
The basic idea is to scan the image in section of blocks of X width and y height. for each block you find the average RGB value and set all those pixels to that color. the smaller the block size the less pixelated.
int avR,avB,avG; // store average of rgb
int pixel;
Bitmap bmOut = Bitmap.createBitmap(width, height, src.getConfig());
for(int x = 0; x < width; x+= pixelationAmount) { // do the whole image
for(int y = 0; y < height; y++ pixelationamount) {
avR = 0; avG = 0; avB =0;
for(int xx =x; xx <pixelationAmount;xx++){// YOU WILL WANT TO PUYT SOME OUT OF BOUNDS CHECKING HERE
for(int yy= y; yy <pixelationAmount;yy++){ // this is scanning the colors
pixel = src.getPixel(x, y);
avR += (int) (color.red(pixel);
avG+= (int) (color.green(pixel);
avB += (int) (color.blue(pixel);
}
}
avrR/= pixelationAmount^2; //divide all by the amount of samples taken to get an average
avrG/= pixelationAmount^2;
avrB/= pixelationAmount^2;
for(int xx =x; xx <pixelationAmount;xx++){// YOU WILL WANT TO PUYT SOME OUT OF BOUNDS CHECKING HERE
for(int yy= y; yy <pixelationAmount;yy++){ // this is going back over the block
bmOut.setPixel(xx, yy, Color.argb(255, avR, avG,avB)); //sets the block to the average color
}
}
}
}
sorry about the bad formatting (wrote it in notepad quickly) but thought it might give you a framework to make your own pixelate function
This is corrected of above algorithm that works:
Bitmap bmOut = Bitmap.createBitmap(OriginalBitmap.getWidth(),OriginalBitmap.getHeight(),OriginalBitmap.getConfig());
int pixelationAmount = 50; //you can change it!!
int width = OriginalBitmap.getWidth();
int height = OriginalBitmap.getHeight();
int avR,avB,avG; // store average of rgb
int pixel;
for(int x = 0; x < width; x+= pixelationAmount) { // do the whole image
for(int y = 0; y < height; y+= pixelationAmount) {
avR = 0; avG = 0; avB =0;
int bx = x + pixelationAmount;
int by = y + pixelationAmount;
if(by >= height) by = height;
if(bx >= width)bx = width;
for(int xx =x; xx < bx;xx++){// YOU WILL WANT TO PUYT SOME OUT OF BOUNDS CHECKING HERE
for(int yy= y; yy < by;yy++){ // this is scanning the colors
pixel = OriginalBitmap.getPixel(xx, yy);
avR += (int) (Color.red(pixel));
avG+= (int) (Color.green(pixel));
avB += (int) (Color.blue(pixel));
}
}
avR/= pixelationAmount^2; //divide all by the amount of samples taken to get an average
avG/= pixelationAmount^2;
avB/= pixelationAmount^2;
for(int xx =x; xx < bx;xx++)// YOU WILL WANT TO PUYT SOME OUT OF BOUNDS CHECKING HERE
for(int yy= y; yy <by;yy++){ // this is going back over the block
bmOut.setPixel(xx, yy, Color.argb(255, avR, avG,avB)); //sets the block to the average color
}
}
}
iv.setImageBitmap(bmOut);
anyway it was not what i was looking for
I have change previous algorithm completely and it really done something like mosaic filter!
the idea is to replace each block pixels with its below block pixels
use this function simply:
public void filter(){
Bitmap bmOut = Bitmap.createBitmap(OriginalBitmap.getWidth(),OriginalBitmap.getHeight(),OriginalBitmap.getConfig());
int pixelationAmount = 10;
Bitmap a = Bitmap.createBitmap(pixelationAmount,pixelationAmount,OriginalBitmap.getConfig());
Bitmap b = Bitmap.createBitmap(pixelationAmount,pixelationAmount,OriginalBitmap.getConfig());
int width = OriginalBitmap.getWidth();
int height = OriginalBitmap.getHeight();
int pixel;
int counter = 1;
int px = 0;int py = 0;int pbx=0;int pby=0;
for(int x = 0; x < width; x+= pixelationAmount) { // do the whole image
for(int y = 0; y < height; y+= pixelationAmount) {
int bx = x + pixelationAmount;
int by = y + pixelationAmount;
if(by >= height) by = height;
if(bx >= width)bx = width;
int xxx = -1;
int yyy = -1;
for(int xx =x; xx < bx;xx++){// YOU WILL WANT TO PUYT SOME OUT OF BOUNDS CHECKING HERE
xxx++;
yyy = -1;
for(int yy= y; yy < by;yy++){ // this is scanning the colors
yyy++;
pixel = OriginalBitmap.getPixel(xx, yy);
if(counter == 1)
{
a.setPixel(xxx, yyy, pixel);
px = x;//previous x
py = y;//previous y
pbx = bx;
pby = by;
}
else
b.setPixel(xxx, yyy, pixel);
}
}
counter++;
if(counter == 3)
{
int xxxx = -1;
int yyyy = -1;
for(int xx =x; xx < bx;xx++)
{
xxxx++;
yyyy = -1;
for(int yy= y; yy <by;yy++){
yyyy++;
bmOut.setPixel(xx, yy, b.getPixel(xxxx, yyyy));
}
}
for(int xx =px; xx < pbx;xx++)
{
for(int yy= py; yy <pby;yy++){
bmOut.setPixel(xx, yy, a.getPixel(xxxx, yyyy)); //sets the block to the average color
}
}
counter = 1;
}
}
}
image_view.setImageBitmap(bmOut);
}
This is the code I used:
ImageFilter is the parent class:
public abstract class ImageFilter {
protected int [] pixels;
protected int width;
protected int height;
public ImageFilter (int [] _pixels, int _width,int _height){
setPixels(_pixels,_width,_height);
}
public void setPixels(int [] _pixels, int _width,int _height){
pixels = _pixels;
width = _width;
height = _height;
}
/**
* a weighted Euclidean distance in RGB space
* #param c1
* #param c2
* #return
*/
public double colorDistance(int c1, int c2)
{
int red1 = Color.red(c1);
int red2 = Color.red(c2);
int rmean = (red1 + red2) >> 1;
int r = red1 - red2;
int g = Color.green(c1) - Color.green(c2);
int b = Color.blue(c1) - Color.blue(c2);
return Math.sqrt((((512+rmean)*r*r)>>8) + 4*g*g + (((767-rmean)*b*b)>>8));
}
public abstract int[] procImage();
}
public class PixelateFilter extends ImageFilter {
int pixelSize;
int[] colors;
/**
* #param _pixels
* #param _width
* #param _height
*/
public PixelateFilter(int[] _pixels, int _width, int _height) {
this(_pixels, _width, _height, 10);
}
public PixelateFilter(int[] _pixels, int _width, int _height, int _pixelSize) {
this(_pixels, _width, _height, _pixelSize, null);
}
public PixelateFilter(int[] _pixels, int _width, int _height, int _pixelSize, int[] _colors) {
super(_pixels, _width, _height);
pixelSize = _pixelSize;
colors = _colors;
}
/* (non-Javadoc)
* #see imageProcessing.ImageFilter#procImage()
*/
#Override
public int[] procImage() {
for (int i = 0; i < width; i += pixelSize) {
for (int j = 0; j < height; j += pixelSize) {
int rectColor = getRectColor(i, j);
fillRectColor(rectColor, i, j);
}
}
return pixels;
}
private int getRectColor(int col, int row) {
int r = 0, g = 0, b = 0;
int sum = 0;
for (int x = col; x < col + pixelSize; x++) {
for (int y = row; y < row + pixelSize; y++) {
int index = x + y * width;
if (index < width * height) {
int color = pixels[x + y * width];
r += Color.red(color);
g += Color.green(color);
b += Color.blue(color);
}
}
}
sum = pixelSize * pixelSize;
int newColor = Color.rgb(r / sum, g / sum, b / sum);
if (colors != null)
newColor = getBestMatch(newColor);
return newColor;
}
private int getBestMatch(int color) {
double diff = Double.MAX_VALUE;
int res = color;
for (int c : colors) {
double currDiff = colorDistance(color, c);
if (currDiff < diff) {
diff = currDiff;
res = c;
}
}
return res;
}
private void fillRectColor(int color, int col, int row) {
for (int x = col; x < col + pixelSize; x++) {
for (int y = row; y < row + pixelSize; y++) {
int index = x + y * width;
if (x < width && y < height && index < width * height) {
pixels[x + y * width] = color;
}
}
}
}
public static final Bitmap changeToPixelate(Bitmap bitmap, int pixelSize, int [] colors) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int[] pixels = new int[width * height];
bitmap.getPixels(pixels, 0, width, 0, 0, width, height);
PixelateFilter pixelateFilter = new PixelateFilter(pixels, width, height, pixelSize, colors);
int[] returnPixels = pixelateFilter.procImage();
Bitmap returnBitmap = Bitmap.createBitmap(returnPixels, width, height, Bitmap.Config.ARGB_8888);
return returnBitmap;
}
}
Here is how you use it:
int [] colors = new int [] { Color.BLACK,Color.WHITE,Color.BLUE,Color.CYAN,Color.RED};
final Bitmap bmOut = PixelateFilter.changeToPixelate(OriginalBitmap, pixelSize,colors);
I've divide my screen up into rects, but I'm using a a for loop so I'm not storing the rects there getting remade each time. How would I store them in like an array?
public void drawGrid() {
//android.os.Debug.waitForDebugger();
int height,width;
int column,row;
int maxColumn,maxRow;
maxColumn = 4;
maxRow = 4;
column = 0;
row = 0;
height = c.getHeight()/maxRow;
width = c.getWidth()/maxColumn;
Paint pg = new Paint();
Rect[] test[];
for(int i = 0;i < 5; i++) {
int srcX = column * width;
int srcY = row * height;
Rect src =new Rect(srcX,srcY,srcX + width, srcY +height);
pg.setColor(Color.WHITE);
pg.setStyle(Paint.Style.STROKE);
pg.setStrokeWidth(5);
c.drawRect(src, pg);
if (column == maxColumn && row == maxRow){
i = 5;
} else {i=0;}
if (column == maxColumn){
row = row + 1;
column = 0;
} else {column = column + 1;}
}
}
Allocate them in advance, so that you're not instantiating objects during a drawing operation. So whenever you determine the number of rects that you'll need (i.e. if it's always the same, initialize them in the constructor). Something like this:
Rect[] rects = new Rect[rectCount];
for(int i = 0; i < rectCount; i++) rects[i] = new Rect();
Then, in your drawing loop, use:
rects[i].set(srcX, srcY, srcX + width, srcY + height);
You should avoid allocating objects during a draw operation whenever possible.
EDIT: For a 2D array:
Rect[][] rects = new Rect[rowCount][colCount];
for(int i = 0; i < rowCount; i++) {
for(int j = 0; j < colCount; j++) {
rects[i][j] = new Rect();
}
}
Then in the loop, it's the same thing:
rects[row][col].set(srcX, srcY, srcX + width, srcY + height);
Rect rectArray[] = new Rect[5];
Then inside the loop:
rectArray[i] = new Rect(srcX,srcY,srcX + width, srcY +height);
Are you always going to have a fixed number of Rectangles?
You might want to consider an Array List?
ArrayList<Rect> rects = new ArrayList<Rect>();
rects.add(new Rect(srcX,srcY,srcX + width, srcY +height));
You can do loads of useful stuff easily with these things, here are some examples:
http://javarevisited.blogspot.com.es/2011/05/example-of-arraylist-in-java-tutorial.html
I have a View, on which I have drawn a checker board
protected void onDraw(Canvas canvas) {
for (int i = 0; i < 8; i ++) {
for (int j = 0; j < 8; j ++) {
float x = j * width;
float y = i * height;
if ((i + j) % 2 == 0) {
canvas.drawRect(x, y, x + width, y + height, lite_square);
}
Now, I want to place an DrawableAnimation object at any random square in the checker board. I need any help/ pointers for solution.