I have a 2d bitmap that I would like to convert into a 3d cube(example like in minecraft: )
I managed to rotate around images in 3d space using the "Camera" but I can't understand how to control it or how to create a cube out of it, anyone has ideas? Please notice i'm allowed only to use canvas and no OpenGL.
Edit:
this is as close as I got:
using this code:
Matrix mMatrix = canvas.getMatrix();
canvas.save();
Camera camera=new Camera();
camera.save();
camera.rotateY(30);
camera.getMatrix(mMatrix);
mMatrix.preTranslate(-30, 0);
mMatrix.postTranslate(30, 0);
canvas.concat(mMatrix);
canvas.drawBitmap(b, 150, 150, null);
canvas.drawBitmap(b, 180, 180, null);
camera.restore();
canvas.restore();
canvas.save();
Okay, so because none helped me I looked for another way of doing it and thought of a workaround way that works, its not efficient and it might slow the program down while doing it, so think twice before using it.
The way I did it is like that:
First of all, I created a cube in paint (could be any 3D shape)
Then, I cut the cube sides and saved them separately.
After loading those images all is left is the code:
public Bitmap CreateACube(Bitmap b2D){
Bitmap result=Bitmap.createBitmap(b2D);
/*loading sides of cube and painting texture on them*/
Bitmap top;
Bitmap left;
Bitmap front;
top=BitmapFactory.decodeResource(getResources(), R.drawable.top);
top=CubeCreator(top, b2D,"top");
left=BitmapFactory.decodeResource(getResources(), R.drawable.left);
left=CubeCreator(left, b2D,"left");
front=BitmapFactory.decodeResource(getResources(), R.drawable.front);
front=CubeCreator(front, b2D,"front");
Bitmap merge;
merge=overlay(top, left);//connecting all cube sides together into one bitmap
merge=overlay(merge, front);
result=Bitmap.createScaledBitmap(merge, merge.getWidth()*2, merge.getHeight()*2, false); //Scaling the result, you can remove if you don't want to.
return result;
}
private Bitmap CubeCreator(Bitmap srcBmp,Bitmap b2D,String s){
/*gets cube side bitmap, the texture bitmap, and a string of the side name*/
int width = srcBmp.getWidth();
int height = srcBmp.getHeight();
int width2=b2D.getWidth();
int height2=b2D.getHeight();
int rows1=0;
int rows2=0;
Bitmap dstBitmap = Bitmap.createBitmap(width, height, Config.ARGB_8888);
/*Running on every pixel in the cube side*/
for (int row = 0; row < height; row++) {
rows1=++rows1%height2; //running on every pixel on the texture and reseting it if reached the last pixel
for (int col = 0; col < width; col++) {
rows2=++rows2%width2;
int pixel = srcBmp.getPixel(col, row);
int alpha = Color.alpha(pixel);
int dstColor=b2D.getPixel(rows2, rows1);
switch(s){//you can add more sides, I used 3
case "front":{
float[] hsv = new float[3];
int color = dstColor;
Color.colorToHSV(color, hsv);
hsv[2] *= 0.8f; // giving brightness to certain sides to make it look more 3D
dstColor = Color.HSVToColor(hsv);
break;
}
case "left":{
float[] hsv = new float[3];
int color = dstColor;
Color.colorToHSV(color, hsv);
hsv[2] *= 0.44f;
dstColor = Color.HSVToColor(hsv);
break;
}
case "top":{
float[] hsv = new float[3];
int color = dstColor;
Color.colorToHSV(color, hsv);
hsv[2] *= 1.2f;
dstColor = Color.HSVToColor(hsv);
break;
}
}
int pixel2=srcBmp.getPixel(col, row);
if(pixel2!= Color.TRANSPARENT)//checking if the current pixel of the side is not transparent
dstBitmap.setPixel(col, row, dstColor);
else{
dstBitmap.setPixel(col, row, pixel2);
}
}
}
return dstBitmap;
}
public static Bitmap overlay(Bitmap bmp1, Bitmap bmp2) {
/*connects two bitmaps together*/
Bitmap bmOverlay = Bitmap.createBitmap(bmp1.getWidth(), bmp1.getHeight(), bmp1.getConfig());
Canvas canvas = new Canvas(bmOverlay);
canvas.drawBitmap(bmp1, new Matrix(), null);
canvas.drawBitmap(bmp2, 0, 0, null);
return bmOverlay;
}
Summary of the code: I run on every pixel of the cube side (front, left, top) and while doing so I also run on every pixel in the texture bitmap, and color the side pixels with the pixels of the texture. After it I connect all colored sides together into one bitmap and return them.
Result:
Related
I'm trying to create a Kaleidoscope with an ImageView in Android. I'm struggling to get the rotation and mirroring for each 'segment' correct. I'm new to image manipulation and I'm trying to adapt the code example from here for android.
I have the following code:
private void drawKaleidoscope() {
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.cropped_landscape);
Bitmap imageview_bitmap = Bitmap.createBitmap(bm.getWidth(), bm.getHeight(), Bitmap.Config.ARGB_8888);
Bitmap matrix_bitmap;
BitmapShader fillShader;
Path triangle_mask = new Path();
RectF r = new RectF(0, 0, bm.getWidth(), bm.getHeight()); // create new rectangle to match the dimensions of our image
this.radius = (int)r.height() / 2;
Canvas c = new Canvas(imageview_bitmap);
c.drawColor(Color.BLACK);
float start_angle = 0;
for (int i = 0; i < this.segments; i++) {
// Create pie-slice shape mask
triangle_mask.reset();
triangle_mask.moveTo(r.centerX(), r.centerY());
triangle_mask.arcTo(r, start_angle, angle);
triangle_mask.close();
// Use odd even check to decide when to mirror the image or not
if (i % 2 == 0) {
Matrix mat = new Matrix();
mat.preTranslate(-radius, -radius);
mat.postRotate(i * angle);
mat.postTranslate(radius, radius);
matrix_bitmap = Bitmap.createBitmap(bm, 0, 0, (int)r.width(), (int)r.height(), mat, true);
}
else {
Matrix mat = new Matrix();
// mirror on x axis
mat.postScale(-1, 1);
mat.postTranslate(-radius, radius);
mat.postRotate((float)-Math.PI);
mat.postRotate(i * angle);
mat.postTranslate(radius, -radius);
matrix_bitmap = Bitmap.createBitmap(bm, 0, 0, (int)r.width(), (int)r.height(), mat, true);
}
fillShader = new BitmapShader(matrix_bitmap, Shader.TileMode.MIRROR, Shader.TileMode.MIRROR);
// Fill the triangle masked area with our image now
Paint fill = new Paint();
fill.setColor(0xFFFFFFFF);
fill.setStyle(Paint.Style.FILL);
fill.setShader(fillShader);
c.drawPath(triangle_mask, fill);
start_angle += angle;
}
kal.setImageBitmap(imageview_bitmap);
}
The output of the above function looks like so:
If anyone could provide some insight on how to properly do the image rotations/mirroring that would be greatly appreciated.
Okay I ended up going about this a different way. Instead of rotating the source image I simply draw the image mask to the same spot on the canvas, and then rotate the canvas itself. Let's say I have 12 image 'slices'. I draw 6 alternating segments, flip the canvas via canvas.scale(-1, 1) and then draw another 6 segments in where the blank spaces are. Here's the code I ended up with:
private Bitmap generateKaleidoscopeBitmap(float start_angle) {
Canvas canvas = new Canvas(imageview_bitmap);
canvas.drawColor(Color.BLACK);
BitmapShader fillShader;
Path triangle_mask = new Path();
RectF r = new RectF(0, 0, imageview_bitmap.getWidth(), imageview_bitmap.getHeight()); // create new rectangle to match the dimensions of our image
int centerX = imageview_bitmap.getWidth() / 2;
int centerY = imageview_bitmap.getHeight() / 2;
// how much to rotate the canvas by after the image is flipped
float offset = calculateCanvasSymmetryOffset(start_angle);
// Create a pie-slice shaped clipping mask
triangle_mask.moveTo(r.centerX(), r.centerY());
triangle_mask.arcTo(r, start_angle, angle);
triangle_mask.close();
// Fill the triangle masked area with our shader now
Paint fill = new Paint();
fill.setColor(0xFFFFFFFF);
fill.setStyle(Paint.Style.FILL);
fillShader = new BitmapShader(source_image, Shader.TileMode.MIRROR, Shader.TileMode.MIRROR);
fill.setShader(fillShader);
// Rotate the canvas and draw the clipping mask to the canvas
for (int i = 0; i < this.segments / 2; i++) {
canvas.drawPath(triangle_mask, fill);
canvas.rotate(angle * 2, centerX, centerY);
}
// mirror the canvas and rotate it once to counter the symmetrical offset
canvas.scale(-1, 1, centerX, centerY);
canvas.rotate(offset, centerX, centerY);
// Rotate the now mirrored canvas and draw the clipping mask to it
// This is a cheap and easy way of creating mirrored segments
for (int i = 0; i < this.segments / 2; i++) {
canvas.drawPath(triangle_mask, fill);
canvas.rotate(angle * 2, centerX, centerY);
}
return imageview_bitmap;
}
We are building a native extension for air, to generate bitmap data from text.
The code below generates the bitmap of a smiley ant "test" those should bee yellow but the color is blue.
http://i.stack.imgur.com/wC1ZH.png
After a lot of searching and trying different example code we are stuck.
public static Bitmap drawText(String text, int textWidth, int textSize, String color) {
try {
text = URLDecoder.decode("%F0%9F%98%8D test", "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
// Get text dimensions
TextPaint textPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG | Paint.LINEAR_TEXT_FLAG);
textPaint.setColor(Color.parseColor("#ffe400"));
textPaint.setTextSize(textSize);
textPaint.setAntiAlias(true);
StaticLayout mTextLayout = new StaticLayout(text, textPaint, textWidth, Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
// Create bitmap and canvas to draw to
Bitmap b = Bitmap.createBitmap(textWidth, mTextLayout.getHeight(), Config.ARGB_8888);
Canvas c = new Canvas(b);
// Draw text
c.save();
c.translate(0, 0);
mTextLayout.draw(c);
c.restore();
Extension.log("Color " + Integer.toString(b.getPixel(15,10), 16));
return b;
}
When logging the returned pixels its already blue so we assume it goes wrong in this function.
It seems that the red and blue color channel are switched.
Fixed it by reversing the blue and red color chanel:
private static Bitmap reversColors(Bitmap b){
int width = b.getWidth();
int height = b.getHeight();
int[] pixels = new int[width * height];
b.getPixels(pixels, 0, width, 0, 0, width, height);
int[] finalArray = new int[width * height];
for(int i = 0; i < finalArray.length; i++) {
int red = Color.red(pixels[i]);
int green = Color.green(pixels[i]);
int blue = Color.blue(pixels[i]);
int alpha = Color.alpha(pixels[i]);
finalArray[i] = Color.argb(alpha, blue, green, red);
}
return Bitmap.createBitmap(finalArray, width, height, Bitmap.Config.ARGB_8888);
}
It is not the best way, but i can't find a better solution
Hi everyone and beforehand thanks, I hope are well write because I am doing a simple application that should unite more than two bitmaps in only one, the problem is in which position bitmaps and size Side wrong, and the truth will not find the back for logic given to me that 's fine, in fact it is a Tengo Que code already in c # and PASE java obviously is different sin but have the same principle .
I wonder if you have the way to make the position and size of these images out as this saying in the code,
Sorry for my bad English
CODIGO JAVA
Paint mPaint;
Bitmap image1=BitmapUtils.decodeBase64(Lie.GeFondo().GetImagen());
Bitmap image2=BitmapUtils.decodeBase64(Utilidades.getImagenTomadabase64());
Bitmap image3=BitmapUtils.decodeBase64(Lie.GetBanner().GetImagen());
Bitmap result = Bitmap.createBitmap(image1.getWidth(), image1.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(result);
Rect srcRect = new Rect(0, 0, image1.getWidth(), image1.getHeight());
Rect dstRect = new Rect(srcRect);
Rect srcRect1 = new Rect( Foto.GetPosicionDeItems().Getx(),Foto.GetPosicionDeItems().Gety(),Foto.GetTamano().GetWidth(), Foto.GetTamano().GeHeight());
Rect srcRect3 = new Rect( Lie.GetBanner().GetPosicionDeItems().Getx(), Lie.GetBanner().GetPosicionDeItems().Gety() ,Lie.GetBanner().GetTamano().GetWidth(), Lie.GetBanner().GetTamano().GeHeight());
Rect srcRect2 = new Rect(0,0,image2.getWidth(), image2.getHeight());
Rect srcRect4 = new Rect(0,0,image3.getWidth(), image3.getHeight());
dstRect.offset(0, 0);
canvas.drawBitmap(image1, srcRect, dstRect, null);
dstRect.offset(image1.getWidth(), 0);
srcRect1.offset(0, 0);
canvas.drawBitmap(image2,srcRect2 ,srcRect1 , null);
srcRect1.offset(image2.getWidth(), 0);
srcRect3.offset(0, 0);
canvas.drawBitmap(image3,srcRect4 ,srcRect3 , null);
srcRect3.offset(image3.getWidth(), 0);
myImage = (ImageView) findViewById(R.id.imageView);
myImage.setImageBitmap(result);
in Java
see java picture http://i58.tinypic.com/1zywm5u.jpg
C# Code
Ignore the foreach.
System.Drawing.Bitmap Bac = (System.Drawing.Bitmap)Lienzo.Fondo.Imagen;
System.Drawing.Graphics r = System.Drawing.Graphics.FromImage(Bac);
if (Lienzo.Fotos != null)
{
if (Lienzo.Fotos.Count > 0)
{
int i = 0;
foreach (RADMLIB.Items item in Lienzo.Fotos)
{
System.Drawing.Bitmap img = (System.Drawing.Bitmap)Lista[i];
r.DrawImage(img, item.PosicionDeItems.X, item.PosicionDeItems.Y, item.Tamano.Width, item.Tamano.Height);
i++;
}
}
}
if (Lienzo.Banner != null)
{
r.DrawImage((System.Drawing.Bitmap)Lienzo.Banner.Imagen, Lienzo.Banner.PosicionDeItems.X, Lienzo.Banner.PosicionDeItems.Y, Lienzo.Banner.Tamano.Width, Lienzo.Banner.Tamano.Height);
}
return Bac;
see c# picture http://i61.tinypic.com/s61wlh.jpg
I found the solution
using Matrix for set location and scale x,y
Bitmap image1=BitmapUtils.decodeBase64(Lie.GeFondo().GetImagen());
Bitmap image2=BitmapUtils.getResizedBitmap(BitmapUtils.decodeBase64(Utilidades.getImagenTomadabase64()),Foto.GetTamano().GetWidth(),Foto.GetTamano().GeHeight());
Bitmap image3=BitmapUtils.getResizedBitmap(BitmapUtils.decodeBase64(Lie.GetBanner().GetImagen()),Lie.GetBanner().GetTamano().GetWidth(),Lie.GetBanner().GetTamano().GeHeight());
Bitmap result = Bitmap.createBitmap(image1.getWidth(), image1.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(result);//Create the canvas to your image
Rect srcRect = new Rect(0, 0, image1.getWidth(), image1.getHeight());
Rect dstRect = new Rect(srcRect);
Matrix matrix = new Matrix ();
Matrix matrix2 = new Matrix ();
matrix.postTranslate( Foto.GetPosicionDeItems().Getx(),Foto.GetPosicionDeItems().Gety());
matrix2.postTranslate( Lie.GetBanner().GetPosicionDeItems().Getx(),Lie.GetBanner().GetPosicionDeItems().Gety());
canvas.drawBitmap(image1, srcRect, dstRect, null);
dstRect.offset(image1.getWidth(), 0);
canvas.drawBitmap(image2,matrix , null);
canvas.drawBitmap(image3,matrix2 , null);
getResizedBitmap Method
public static Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {
int width = bm.getWidth();
int height = bm.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
return resizedBitmap;
}
see the image
https://lh4.ggpht.com/LXW8kVc3U8qQUHnORI-3H4H-A2hjq92y_oEDsKIs-iBDkVBFTgjGP03xFReCeuyLlg=h900-rw
I currently have a maze game which draws a 5 x 5 square (takes the width of screen and splits it evenly). Then for each of these boxes using x and y cordinates I user drawRect, to draw a colored background.
The issue I am having is I now need to draw an image within this same location, therefore replacing the current plain background colour fill.
Here is the code I am currently using to drawRect (a few example):
// these are all the variation of drawRect that I use
canvas.drawRect(x, y, (x + totalCellWidth), (y + totalCellHeight), green);
canvas.drawRect(x + 1, y, (x + totalCellWidth), (y + totalCellHeight), green);
canvas.drawRect(x, y + 1, (x + totalCellWidth), (y + totalCellHeight), green);
I would then also need to implement a background image for all the other squares within my canvas. This background will have simple 1px black lines drawn over the top of it, current code to draw in a grey background.
background = new Paint();
background.setColor(bgColor);
canvas.drawRect(0, 0, width, height, background);
Could you please advice if this is at all possible. If so, what is the best way I can go about doing this, whilst trying to minimise memory usage and having 1 image which will expand and shrink to fill the relvent square space(this varies on all the different screen sizes as it splits the overall screen width evenly).
Use the Canvas method public void drawBitmap (Bitmap bitmap, Rect src, RectF dst, Paint paint). Set dst to the size of the rectangle you want the entire image to be scaled into.
EDIT:
Here's a possible implementation for drawing the bitmaps in squares across on the canvas. Assumes the bitmaps are in a 2-dimensional array (e.g., Bitmap bitmapArray[][];) and that the canvas is square so the square bitmap aspect ratio is not distorted.
private static final int NUMBER_OF_VERTICAL_SQUARES = 5;
private static final int NUMBER_OF_HORIZONTAL_SQUARES = 5;
...
int canvasWidth = canvas.getWidth();
int canvasHeight = canvas.getHeight();
int squareWidth = canvasWidth / NUMBER_OF_HORIZONTAL_SQUARES;
int squareHeight = canvasHeight / NUMBER_OF_VERTICAL_SQUARES;
Rect destinationRect = new Rect();
int xOffset;
int yOffset;
// Set the destination rectangle size
destinationRect.set(0, 0, squareWidth, squareHeight);
for (int horizontalPosition = 0; horizontalPosition < NUMBER_OF_HORIZONTAL_SQUARES; horizontalPosition++){
xOffset = horizontalPosition * squareWidth;
for (int verticalPosition = 0; verticalPosition < NUMBER_OF_VERTICAL_SQUARES; verticalPosition++){
yOffset = verticalPosition * squareHeight;
// Set the destination rectangle offset for the canvas origin
destinationRect.offsetTo(xOffset, yOffset);
// Draw the bitmap into the destination rectangle on the canvas
canvas.drawBitmap(bitmapArray[horizontalPosition][verticalPosition], null, destinationRect, null);
}
}
Try the following code :
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setFilterBitmap(true);
paint.setDither(true);
canvas.drawBitmap(bitmap, x, y, paint);
==================
You could also just reference this answer.
I am saving an image from the camera that was in landscape mode. so it gets saved in landscape mode and then i apply an overlay onto it that too is in landscape mode. I want to rotate that image and then save. e.g. if i have this
I want to rotate clockwise by 90 degrees once and make it this and save it to sdcard:
How is this to be accomplished?
void rotate(float x)
{
Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(),R.drawable.tedd);
int width = bitmapOrg.getWidth();
int height = bitmapOrg.getHeight();
int newWidth = 200;
int newHeight = 200;
// calculate the scale - in this case = 0.4f
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
matrix.postRotate(x);
Bitmap resizedBitmap = Bitmap.createBitmap(bitmapOrg, 0, 0,width, height, matrix, true);
iv.setScaleType(ScaleType.CENTER);
iv.setImageBitmap(resizedBitmap);
}
Check this
public static Bitmap rotateImage(Bitmap src, float degree)
{
// create new matrix
Matrix matrix = new Matrix();
// setup rotation degree
matrix.postRotate(degree);
Bitmap bmp = Bitmap.createBitmap(src, 0, 0, src.getWidth(), src.getHeight(), matrix, true);
return bmp;
}
You can use the Canvas API to do that. Note that you need to switch width and height.
final int width = landscapeBitmap.getWidth();
final int height = landscapeBitmap.getHeight();
Bitmap portraitBitmap = Bitmap.createBitmap(height, width, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(portraitBitmap);
c.rotate(90, height/2, width/2);
c.drawBitmap(landscapeBitmap, 0,0,null);
portraitBitmap.compress(CompressFormat.JPEG, 100, stream);
Use a Matrix.rotate(degrees) and draw the Bitmap to it's own Canvas using that rotating matrix. I don't know though if you might have to make a copy of the bitmap before drawing.
Use Bitmap.compress(...) to compress your bitmap to an outputstream.
The solution of Singhak works fine.
In case you need fit the size of result bitmap (perhaps for ImageView) you can expand the method as follows:
public static Bitmap rotateBitmapZoom(Bitmap bmOrg, float degree, float zoom){
Matrix matrix = new Matrix();
matrix.postRotate(degree);
float newHeight = bmOrg.getHeight() * zoom;
float newWidth = bmOrg.getWidth() / 100 * (100.0f / bmOrg.getHeight() * newHeight);
return Bitmap.createBitmap(bmOrg, 0, 0, (int)newWidth, (int)newHeight, matrix, true);
}