Rotate image in android - android

I want rotate image in both the ways Clockwise as well as Anti clock wise.
I had try but not rotate image both the way,
so plz give me solution for my problem if you know..
Thanks in Advance.................///

Use the code below
public class Rotateimage extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gallery);
// or just load a resource from the res/drawable directory:
Bitmap myBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.flo);
// find the width and height of the screen:
Display d = getWindowManager().getDefaultDisplay();
int x = d.getWidth();
int y = d.getHeight();
// get a reference to the ImageView component that will display the image:
ImageView img1 = (ImageView)findViewById(R.id.imageView1);
// scale it to fit the screen, x and y swapped because my image is wider than it is tall
Bitmap scaledBitmap = Bitmap.createScaledBitmap(myBitmap, y, x, true);
// create a matrix object
Matrix matrix = new Matrix();
matrix.postRotate(45, 90, 180);
// create a new bitmap from the original using the matrix to transform the result
Bitmap rotatedBitmap = Bitmap.createBitmap(scaledBitmap , 0, 0, scaledBitmap .getWidth(), scaledBitmap .getHeight(), matrix, true);
// display the rotated bitmap
img1.setImageBitmap(rotatedBitmap);
}}

Here is the base code to load a bitmap and rotate it left or right:
// Load a bitmap from a drawable, make sure this drawable exists in your project
Bitmap sprite = BitmapFactory.decodeResource(this.getResources(),
R.drawable.ic_launcher);
// Create two matrices that will be used to rotate the bitmap
Matrix rotateRight = new Matrix();
Matrix rotateLeft = new Matrix();
// Set the matrices with the desired rotation 90 or -90 degrees
rotateRight.preRotate(90);
rotateLeft.preRotate(-90);
// Create bitmaps based on the loaded bitmap 'sprite' and apply one of
// the rotation matrices
Bitmap rSprite = Bitmap.createBitmap(sprite, 0, 0,
sprite.getWidth(), sprite.getHeight(), rotateRight, true);
Bitmap lSprite = Bitmap.createBitmap(sprite, 0, 0,
sprite.getWidth(), sprite.getHeight(), rotateLeft, true);
Now go and use rSprite and lSprite.
Here is a full sample that actually draws the bitmaps to screen:
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new drawView(this));
}
private class drawView extends View{
public drawView(Context context){
super(context);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// Load a bitmap from a drawable, make sure this drawable exists in your project
Bitmap sprite = BitmapFactory.decodeResource(this.getResources(),
R.drawable.ic_launcher);
// Create two matrices that will be used to rotate the bitmap
Matrix rotateRight = new Matrix();
Matrix rotateLeft = new Matrix();
// Set the matrices with the desired rotation 90 or -90 degrees
rotateRight.preRotate(90);
rotateLeft.preRotate(-90);
// Create bitmaps based on the loaded bitmap 'sprite' and apply one of
// the rotation matrices
Bitmap rSprite = Bitmap.createBitmap(sprite, 0, 0,
sprite.getWidth(), sprite.getHeight(), rotateRight, true);
Bitmap lSprite = Bitmap.createBitmap(sprite, 0, 0,
sprite.getWidth(), sprite.getHeight(), rotateLeft, true);
//Draw the first unrotated sprite at the top left of the screen
canvas.drawBitmap(sprite, 0, 0, null);
//Draw the rotated right sprite on the 2nd row
canvas.drawBitmap(rSprite, 0, sprite.getHeight() + 5, null);
//Draw the rotated left sprite on the 3rd row
canvas.drawBitmap(lSprite, 0, sprite.getHeight() * 2 + 5, null);
}
}
}

use this code hope it will be helpful...
you must have to write this method to do rotate operation
public void paintFromCenter(float angle, Canvas c) {
Bitmap b = sprite;
Bitmap h = b;
Matrix matrix = new Matrix();
matrix.postRotate(angle, h.getWidth() / 2, h.getHeight());
matrix.postTranslate(getX(), getY());
// canvas.drawBitmap(bitmap, matrix, new Paint());
Bitmap bmp2 = Bitmap.createBitmap(h, 0, 0, frameWidth, frameHeight,
matrix, true);
c.drawBitmap(h, matrix, null);
}
in your program you have to write onTouchEvent() method
public boolean onTouchEvent(MotionEvent event) {
int action = event.getAction();
if (action == MotionEvent.ACTION_DOWN) {
edX = (int) event.getX();
edY = (int) event.getY();
if ((edX > objectSprite.getX()
&& edX < objectSprite.getX() + objectSprite.getWidth()
&& edY > objectSprite.getY() && edY < objectSprite.getY()
+ objectSprite.getHeight())) {
}
}
if (action == MotionEvent.ACTION_MOVE) {
emX = (int) event.getX();
emY = (int) event.getY();
if (edX < emX && angle <= 90) {
update(canvas);
CHAR = 'D';
} else if (edX > emX && angle > 0) {
update(canvas);
CHAR = 'U';
}
if (edY < emY && angle <= 90) {
update(canvas);
CHAR = 'L';
} else if (edY > emY && angle >= 0) {
update(canvas);
CHAR = 'R';
}
}
return true;
}
and you have to create update() method to rotate your angle on touch event angle can be define as your choice. Initially i have declare
int angle=1;
public void update(Canvas canvas) {
switch (CHAR) {
case 'D':
angle += 1;
break;
case 'U':
angle -= 1;
break;
case 'R':
angle -= 1;
break;
case 'L':
angle += 1;
break;
}
}
Now you have to draw your object in draw() method like this
public void draw() {
objectSprite.paintFromCenter(angle, canvas);
}

You just add this simple code to your button
imVCature_pic.setRotation(imVCature_pic.getRotation() + 90);

Matrix mat = new Matrix();
mat.preRotate(angle);///in degree
Bitmap mBitmap = Bitmap.createBitmap(originalBmp, 0, 0, modWidth, modHeight, mat, true);
//originalBmp -> original img as bitmap
//modHeight -> new height
//modWidth -> new width
use the above code.

Related

How to pass many textview on random position over image view?

now I am getting only one Text over the image I am using Canvas and Bitmap :
here is my code :
public Bitmap drawTextArrayToBitmap(Context mContext, int resourceId,String mText) {
try {
Resources resources = mContext.getResources();
float scale = resources.getDisplayMetrics().density;
Bitmap bitmap = BitmapFactory.decodeResource(resources, resourceId);
android.graphics.Bitmap.Config bitmapConfig = bitmap.getConfig();
if(bitmapConfig == null) {
bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888;
}
bitmap = bitmap.copy(bitmapConfig, true);
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(Color.rgb(110,110, 110));
paint.setTextSize((int) (12 * scale));
paint.setShadowLayer(1f, 0f, 1f, Color.DKGRAY);
Rect bounds = new Rect();
paint.getTextBounds(mText, 0, mText.length(), bounds);
/* int x = (bitmap.getWidth() - bounds.width())/6;
int y = (bitmap.getHeight() + bounds.height())/5;*/
int x = 100, y = 100;
for(int i=0;i<20;i++)
{
canvas.drawText(mText, x * scale, y * scale, paint);
}
return bitmap;
} catch (Exception e) {
// TODO: handle exception
return null;
}
}
inside oncreate ;
ImageView mImageView = (ImageView)findViewById(R.id.imageView1);
// Bitmap bmp =drawTextToBitmap(this,R.drawable.man,"Hello Android");
Bitmap bmp =drawTextArrayToBitmap(this,R.drawable.man,"Smile");
mImageView.setImageBitmap(bmp);
In this above code, I want to add multiple texts on random position over Image and different style I have tried much time I could not get succeed yet. I have tried inside loop also.
Thank you in Advance I would appreciate your effort

How to combine two bitmaps in Android

The first bitmap is set to fill the entire canvas. I then add another bitmap that has been created from an imageview using:
tattoo.buildDrawingCache();
Bitmap bit2 = tattoo.getDrawingCache();
I then want to add this bitmap over the other keeping it's same scale, rotation, and translation relative to the other bitmap. My issue is that, while the scale and rotation seem fine, the translation shifts to one side or the other.
public static Bitmap overlay(Bitmap bmp1, Bitmap bmp2) {
Bitmap bmOverlay = Bitmap.createBitmap(bmp1.getWidth(), bmp1.getHeight(), bmp1.getConfig());
Canvas canvas = new Canvas(bmOverlay);
canvas.drawBitmap(bmp1, 0,0 , null);
Matrix matrix = new Matrix();
matrix.setScale(tattoo.getScaleX() / imageView.getScaleX(), tattoo.getScaleY() / imageView.getScaleY());
int[] tattooCoords = getRelativeCoords(tattoo);
int[] imageViewCoords = getRelativeCoords(imageView);
matrix.setTranslate(tattooCoords[0] - imageViewCoords[0], tattooCoords[1] - imageViewCoords[1]);
matrix.postRotate(tattoo.getRotation(), tattoo.getX() + tattoo.getWidth() / 2,
tattoo.getY() + tattoo.getHeight() / 2);
canvas.drawBitmap(bmp2, matrix, null);
bmp1.recycle();
bmp2.recycle();
return bmOverlay;
}
private static int[] getRelativeCoords(View v){
View parent = v.getRootView();
int[] viewLocation = new int[2];
v.getLocationInWindow(viewLocation);
int[] rootLocation = new int[2];
parent.getLocationInWindow(rootLocation);
int relativeLeft = viewLocation[0] - rootLocation[0];
int relativeTop = viewLocation[1] - rootLocation[1];
return new int[]{relativeLeft, relativeTop};
}
public static Bitmap combineBitmap(Bitmap background, Bitmap foreground) {
Bitmap result;
try {
if (background == null) {
return null;
}
int bgWidth = background.getWidth();
int bgHeight = background.getHeight();
int fgWidth = foreground.getWidth();
int fgHeight = foreground.getHeight();
result = Bitmap.createBitmap(bgWidth, bgHeight, Config.ARGB_8888);
Canvas cv = new Canvas(result);
cv.drawBitmap(background, 0, 0, null);
cv.drawBitmap(foreground, (bgWidth - fgWidth) / 2, (bgHeight - fgHeight) / 2, null);
cv.save(Canvas.ALL_SAVE_FLAG);
cv.restore();
return result;
} catch (Exception e) {
return null;
}
}
Check whether both Images have equal images have same height and width, then check for every pixel is equal.
boolean imagesEqualCheck(Image img1, Image img2)
{
if (img1.getHeight() != img2.getHeight()) return false;
if (img1.getWidth() != img2.getWidth()) return false;
for (int y = 0; y < img1.getHeight(); ++y)
for (int x = 0; x < img1.getWidth(); ++x)
if (img1.getPixel(x, y) != img2.getPixel(x, y)) return false;
return true;
}

Draw Bitmap in Custom ImageView and get the Co-ordinates of the ImageView irrespective of the device

I want to get the co-ordinates of the ImageView, Irrespective of device size.
Is there any possible way !!
I have tried to create specific size for the ImageView,Even specific size for the Parent View also ,but its not working.
I have tried the following possible ways.
int[] posXY = new int[2];
imageview.getLocationOnScreen(posXY);
int MoveX = posXY[0];
int MoveY = posXY[1];
I have tried with Matrix too ,But not working.
Matrix m = imageview.getImageMatrix();
Tried the below code, but it is also not working.!!
I need to get the same {x,y} Co-ordinates for all devices for the same point (Location).
final float[] getPointerCoords(ImageView view, MotionEvent e)
{
final int index = e.getActionIndex();
final float[] coords = new float[] {
e.getX(index), e.getY(index)
};
Matrix matrix = new Matrix();
view.getImageMatrix().invert(matrix);
matrix.mapPoints(coords);
return coords;
}
Here is draw Method :
if i set bitmap image in draw, it does not fit the screen for every devices. If i set image with Display width and height, i am getting different co-ordinates.
#Override
public void draw(Canvas canvas) {
// TODO Auto-generated method stub
super.draw(canvas);
Resources res = getResources();
Drawable drawable = res.getDrawable(R.drawable.subimage);
mBitmap = ((BitmapDrawable) drawable).getBitmap();
canvas.drawBitmap(mBitmap, 0, 0, null);
}
Any Idea or help would be really helpful.
You have to calculate your device screen ratio first,
deviceWidth / screenHeight = ratio
then you have to multiply it with your desired coordinate :
ratio * xCoord = newXcoord; // and same for Y coord
By doing this you will keep the equivalent coordinates for all device sizes.
Also you may declare sizes and coordinates with respect to % of screen dimensions like :
x = 0.2 * deviceWidth // %20 of device width from left
Finally found some relative solution,Same Co-ordinates for all devices.Using Activity,no Custom ImageView.
On ImageView OnTouch ..
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
final int index = e.getActionIndex();
final float[] coords = new float[] {
e.getX(index), e.getY(index)
};
Matrix matrix = new Matrix();
choosenImageView.getImageMatrix().invert(matrix);
matrix.mapPoints(coords);
return true;
}
Draw Using Canvas
Resources res = getResources();
Drawable drawable = res.getDrawable(R.drawable.image);
Bitmap bmp= ((BitmapDrawable) drawable).getBitmap();
alteredBitmap = Bitmap.createBitmap(bmp.getWidth(), bmp.getHeight(), bmp.getConfig());
canvas = new Canvas(alteredBitmap);
paint = new Paint();
paint.setColor(Color.GREEN);
paint.setStrokeWidth(5);
matrix = new Matrix();
canvas.drawBitmap(bmp, matrix, paint);
You can try this
imageview.post(new Runnable() {
#Override
public void run() {
int[] posXY = new int[2];
imageview.getLocationOnScreen(posXY);
int MoveX = posXY[0];
int MoveY = posXY[1];
Log.i("xy co-ordinate", "x "+MoveX, "y"+MoveY);
}
});

How to rotate image through onTouchListener?

I have to implement functionality to rotate image through onTouchListener(). Please provide me sample code to rotate image. Please help me.
Thanks in Advance.
Here is sample code to rotate an image.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
baseView = (View) findViewById(R.id.baseView);
turntable = (ImageView) findViewById(R.id.turntable);
turntable.setOnTouchListener(onTableTouched);
baseView.setOnTouchListener(onTableTouched);
}
public android.view.View.OnTouchListener onTableTouched = new android.view.View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent evt) {
double r = Math.atan2(evt.getX() - turntable.getWidth() / 2,
(turntable.getHeight() / 2) - evt.getY());
int rotation = (int) Math.toDegrees(r);
Log.i("R is ", ""+r);
if (evt.getAction() == MotionEvent.ACTION_DOWN) {
}
if (evt.getAction() == MotionEvent.ACTION_MOVE) {
x= evt.getX();
y= evt.getY();
updateRotation(rotation);
}
if (evt.getAction() == MotionEvent.ACTION_UP) {
//
}
return true;
}
};
private void updateRotation(double rot) {
float newRot = new Float(rot);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
R.drawable.orsl_circle_transparent);
Matrix matrix = new Matrix();
// matrix.setTranslate(getWindowManager().getDefaultDisplay().getWidth()/2, getWindowManager().getDefaultDisplay().getHeight());
matrix.postRotate(newRot,bitmap.getWidth()/2,bitmap.getHeight()/2);
// matrix.setSinCos(newRot, newRot/2, 100, 100);
// matrix.postRotate(newRot);
Log.i("THE ROATTION ", " "+ newRot);
if(y>250)
{
Bitmap redrawnBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap
.getWidth(), bitmap.getHeight(), matrix, true);
turntable.setImageBitmap(redrawnBitmap);
}else
{
Bitmap redrawnBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap
.getWidth(), bitmap.getHeight(), matrix, true);
turntable.setImageBitmap(redrawnBitmap);
Log.i("GUITAR _IMAGE", "");
}
}
you need to use an xml in type of "tween animation".
than, from the java code you can make a view act acording to this xml.
here is a link that help:
http://www.edumobile.org/android/android-beginner-tutorials/tween-animation/

Combine two bitmap and save as jpg format in android?

i have two bitmap in my project what i need is that i need to combine those two bit map and combine those bit map to a single image i will show my code
public class FotosurpriseActivity extends Activity {
/** Called when the activity is first created. */
Bitmap overlay;
Paint pTouch;
int X = -100;
int Y = -100;
Canvas c2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
requestWindowFeature(Window.FEATURE_NO_TITLE);
Bitmap mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.android);
Bitmap mBitmapover = BitmapFactory.decodeResource(getResources(), R.drawable.ss);
overlay = BitmapFactory.decodeResource(getResources(),R.drawable.ss).copy(Config.ARGB_8888, true);
c2 = new Canvas(overlay);
pTouch = new Paint(Paint.ANTI_ALIAS_FLAG);
// pTouch.setXfermode(new PorterDuffXfermode(Mode.TARGET);
pTouch.setColor(Color.TRANSPARENT);
pTouch.setMaskFilter(new BlurMaskFilter(15, Blur.NORMAL));
setContentView(new BitMapView(this, mBitmap,mBitmapover));
}
class BitMapView extends View {
Bitmap mBitmap = null;
Bitmap mBitmapover = null;
public BitMapView(Context context, Bitmap bm, Bitmap bmover) {
super(context);
mBitmap = bm;
mBitmapover = bmover;
}
#Override
public boolean onTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN: {
X = (int) ev.getX();
Y = (int) ev.getY();
invalidate();
break;
}
case MotionEvent.ACTION_MOVE: {
X = (int) ev.getX();
Y = (int) ev.getY();
invalidate();
break;
}
case MotionEvent.ACTION_UP:
break;
}
return true;
}
#Override
protected void onDraw(Canvas canvas) {
// called when view is drawn
Paint paint = new Paint();
paint.setFilterBitmap(true);
// The image will be scaled so it will fill the width, and the
// height will preserve the image’s aspect ration
/* double aspectRatio = ((double) mBitmap.getWidth()) / mBitmap.getHeight();
Rect dest = new Rect(0, 0, this.getWidth(),(int) (this.getHeight() / aspectRatio));
double aspectRatio2 = ((double) mBitmapover.getWidth()) / mBitmapover.getHeight();
Rect dest2 = new Rect(0, 0, this.getWidth(),(int) (this.getHeight() / aspectRatio2));
canvas.drawBitmap(mBitmap, null, dest, paint);
canvas.drawBitmap(mBitmapover, null, dest2, paint); */
//draw background
canvas.drawBitmap(mBitmap, 0, 0, null);
//copy the default overlay into temporary overlay and punch a hole in it
c2.drawBitmap(mBitmapover, 0, 0, null); //exclude this line to show all as you draw
c2.drawCircle(X, Y, 80, pTouch);
//draw the overlay over the background
canvas.drawBitmap(overlay, 0, 0, null);
}
}
}
how can i make this happen?
The onDraw function draws to the view. You don't actually need to do that at all. You can do this all in memory where the bitmaps reside. You draw the other bitmap on C2 as well. You don't have to draw anything to canvas in the onDraw() all that does is draw that to the screen.

Categories

Resources