I am using seekbar to scale the image. The image is scaled to one specific size, where ever you take the seekbar and its scaled for the once, next time you change the progress of seekbar the image remains in same changed size. I want to scale it dynamically with the increase or decrease of seekbar progress.
Seekbar code snippet
seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStartTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProgressChanged(SeekBar seekBar, int progresValue,
boolean fromUser) {
// TODO Auto-generated method stub
Log.i("Test", "Progress value = " + Integer.toString(progresValue));
Log.i("Test", "Image width = " + Integer.toString(width));
Log.i("Test", "Image height = " + Integer.toString(height));
scaleImage(image, width, height);
}
});
Function to scale image
public void scaleImage(Bitmap bitmap, int w, int h) {
// Get current dimensions AND the desired bounding box
int bounding = dpToPx(150);
Log.i("Test", "original width = " + Integer.toString(w));
Log.i("Test", "original height = " + Integer.toString(h));
Log.i("Test", "bounding = " + Integer.toString(bounding));
// Determine how much to scale: the dimension requiring less scaling is
// closer to the its side. This way the image always stays inside your
// bounding box AND either x/y axis touches it.
float xScale = ((float) bounding) / w;
float yScale = ((float) bounding) / h;
float scale = (xScale <= yScale) ? xScale : yScale;
Log.i("Test", "xScale = " + Float.toString(xScale));
Log.i("Test", "yScale = " + Float.toString(yScale));
Log.i("Test", "scale = " + Float.toString(scale));
// Create a matrix for the scaling and add the scaling data
Matrix matrix = new Matrix();
matrix.postScale(scale, scale);
// Create a new bitmap and convert it to a format understood by the
// ImageView
Bitmap scaledBitmap = Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix,
true);
sWidth = scaledBitmap.getWidth(); // re-use
sHeight = scaledBitmap.getHeight(); // re-use
#SuppressWarnings("deprecation")
BitmapDrawable result = new BitmapDrawable(scaledBitmap);
Log.i("Test", "scaled width = " + Integer.toString(sWidth));
Log.i("Test", "scaled height = " + Integer.toString(sHeight));
qrImage.setImageDrawable(result);
}
Function to make a bounding box
private int dpToPx(int dp) {
float density = getActivity().getApplicationContext().getResources()
.getDisplayMetrics().density;
return Math.round((float) dp * density);
}
use below code for resize your image using seekbar
public class MyActivity extends Activity {
private static final int WIDTH_SCALE_RATIO = 10;
private static final int HEIGHT_SCALE_RATIO = 10;
private int previousProcess = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ImageView img = (ImageView) findViewById(R.id.img);
((SeekBar) findViewById(R.id.seekBar))
.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar arg0) {
}
#Override
public void onStartTrackingTouch(SeekBar arg0) {
}
#Override
public void onProgressChanged(SeekBar seekBar,
int progresValue, boolean fromUser) {
int diff = progresValue - previousProcess;
scaleImage(img, diff);
previousProcess = progresValue;
}
});
}
public void scaleImage(ImageView img, int scale) {
Bitmap bitmap = ((BitmapDrawable) img.getDrawable()).getBitmap();
float width = bitmap.getWidth();
float height = bitmap.getHeight();
width += scale * WIDTH_SCALE_RATIO;
height += scale * HEIGHT_SCALE_RATIO;
bitmap = Bitmap.createScaledBitmap(bitmap, (int) width, (int) height,
true);
img.setImageBitmap(bitmap);
}
}
Related
I'm working with camera2 and I'm showing a preview of my photo/video after longclick in my thumbnail. Also, I'm rotating it depending of which orientation the camera had when the picture was taken. For example, if I did a picture in 90º, my preview will be also rotated 90º.
Everything is working fine, I'm using a customContainer and there I'm using onLayout and OnMeasure to create my preview depending of the size of the screen, aspect ratio and orientation. It works fine with photos. My problem appear when I try to do the same with videos, they only work in 0º.
I tried to rotate the TextureView which contain my MediaPlayer but after this my onLayout become crazy and Itś impossible find a (l,t,r,b) combination to measure it correctly.
Here is my XML:
<?xml version="1.0" encoding="utf-8"?>
<com.android.camera.ui.common.ThumbnailContainer xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/preview_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/rounded_rectangle_thumbnail_preview"
android:visibility="invisible">
<TextureView
android:id="#+id/show_video_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="invisible"/>
<ImageView
android:id="#+id/image_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:adjustViewBounds="true"
android:visibility="invisible"
/>
</com.android.camera.ui.common.ThumbnailContainer>
Here is my Surface code:
#Override
public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
Log.i(TAG, "InicializoSurface. Width: " + width + " HEIGHT:" + height);
Log.i(TAG, "InicializoSurface. Width: " + mVideoView.getMeasuredWidth() + " HEIGHT:" + mVideoView.getMeasuredHeight());
Log.i(TAG, "View transform. Width: " + mVideoView.getWidth() + " HEIGHT:" + mVideoView.getHeight());
mMediaSurface = new Surface(mVideoView.getSurfaceTexture());
initializeMediaPlayer();
}
#Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
}
#Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
if (mMediaPlayer != null) {
// Make sure we stop video and release resources when activity is destroyed.
mMediaPlayer.stop();
mMediaPlayer.release();
mMediaPlayer = null;
}
return false;
}
#Override
public void onSurfaceTextureUpdated(SurfaceTexture surface) {
}
//////////
private void initializeMediaPlayer(){
mMediaPlayer = new CustomMediaPlayer();
Uri uri = Uri.parse(mCameraDataAdapter.getList().get(0).getPath());
try {
mMediaPlayer.setDataSource(mActivity, uri);
mMediaPlayer.setSurface(mMediaSurface);
mMediaPlayer.prepareAsync();
mMediaPlayer.setOnPreparedListener(mMediaPlayer);
mMediaPlayer.setOnCompletionListener(mMediaPlayer);
} catch (IOException e) {
e.printStackTrace();
}
}
///////////
mVideoView.setVisibility(View.VISIBLE);
// mVideoView.setTranslationX(-200);
// mVideoView.setTranslationY(-200);
Log.i(TAG, "X: " + mVideoView.getX() + "Y: " + mVideoView.getY());
if (mVideoView.isAvailable()) {
onSurfaceTextureAvailable(mVideoView.getSurfaceTexture(), mVideoView.getWidth(), mVideoView.getHeight());
}
if (mMediaPlayer == null) {
initializeMediaPlayer();
}
// mMediaPlayer.mVideoHolder = mVideoView.getHolder();
// mMediaPlayer.setDisplay(mMediaPlayer.mVideoHolder);
if (mMediaPrepared) {
Log.i(TAG,"Comienzo Video");
mMediaPlayer.start();
}
Finally here is my onMeasure/OnLayout from my CustomView
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width;
int height;
int wantedWidth = 0;
int wantedHeight = 0;
if(mWidth == 0 && mHeight == 0 ){
mWidth = MeasureSpec.getSize(widthMeasureSpec);
mHeight =MeasureSpec.getSize(heightMeasureSpec);
}
width = mWidth;
height = mHeight;
if (mOrientation == 0 || mOrientation == 180) {
wantedWidth = width - (int)(mMargin * 2);
mVideo.measure(MeasureSpec.makeMeasureSpec(wantedWidth, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec((int) (wantedWidth * mVideoAspectRatio), MeasureSpec.EXACTLY));
wantedHeight = (mViewTop.getLayoutParams().height) * 2 + (int) (wantedWidth * mAspectRatio);
} else {
Log.e(TAG, "Real Width = " + width + " real Height = " + height);
wantedHeight = width - 2 * mViewTop.getLayoutParams().height - (int)(mMargin * 2);
mVideo.measure(MeasureSpec.makeMeasureSpec(wantedHeight, MeasureSpec.EXACTLY),MeasureSpec.makeMeasureSpec((int) (wantedHeight * mAspectRatio), MeasureSpec.EXACTLY));
//
wantedWidth =(int) (wantedHeight * mAspectRatio) ;
wantedHeight = width - (int)(mMargin * 2);
}
Log.e(TAG, "onMeasure: " + wantedWidth + "x" + wantedHeight);
setMeasuredDimension(MeasureSpec.makeMeasureSpec(wantedWidth, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(wantedHeight, MeasureSpec.EXACTLY));
}
#Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
int w = getMeasuredWidth();
int h = getMeasuredHeight();
int viewHeight = mViewBottom.getMeasuredHeight();
int imageViewHeight = mImage.getMeasuredHeight();
int wantedHeight = 0;
// w = w - (int) (2 * mMargin);
if (mOrientation == 0 || mOrientation == 180) {
mVideo.layout(0,wantedHeight,w,wantedHeight + imageViewHeight);
}else{
mVideo.layout(viewHeight,0,r-viewHeight - (int) mMargin,w);
}
}
I have been looking in other post as Android MediaRecorder making rotated video and I saw that it's not possible to rotate the textureView, but I can't believe that I can rotate a image so easily and have to fight during this to rotate 90 degrees a video.
Thanks to #pskink for their comments in the post I found a solution with him. Finally I used a Matrix to rotate the Video Container(Texture View). The method that pskink give me is the next one:
private void setupMatrix(int width, int height, int degrees, boolean isHorizontal) {
Log.d(TAG, "setupMatrix for " + degrees + " degrees");
Matrix matrix = new Matrix();
//The video will be streched if the aspect ratio is in 1,5(recording at 480)
RectF src;
if (isHorizontal)
//In my case, I changed this line, because with my onMeasure() and onLayout() methods my container view is already rotated and scaled, so I need to sent the inverted params to the src.
src = new RectF(0, 0,mThumbnailContainer.getmWidth(), mThumbnailContainer.getmHeight());
else
src = new RectF(0, 0, mThumbnailContainer.getmWidth(),mThumbnailContainer.getmHeight());
RectF dst = new RectF(0, 0, width, height);
RectF screen = new RectF(dst);
Log.d(TAG, "Matrix: " + width + "x" + height);
Log.d(TAG, "Matrix: " + mThumbnailContainer.getmWidth() + "x" + mThumbnailContainer.getmHeight());
matrix.postRotate(degrees, screen.centerX(), screen.centerY());
matrix.mapRect(dst);
matrix.setRectToRect(src, dst, Matrix.ScaleToFit.CENTER);
matrix.mapRect(src);
matrix.setRectToRect(screen, src, Matrix.ScaleToFit.FILL);
matrix.postRotate(degrees, screen.centerX(), screen.centerY());
mVideoView.setTransform(matrix);
}
Finally it worked and it looks totally awesome. With this I have been able to rotate and scale any video totally dynamically depending of the screen of my device and the Aspect Ratio used for record the video or take the picture.
I am trying to set a sprite image as a background
and I didn't success to set the image size to screen size.
I'm trying this:
public class Game extends SurfaceView implements Runnable {
private SurfaceHolder holder;
private boolean isRunning = false;
private Thread gameThread;
private Sprite s;
private int screenWidth;
private int screenHeight;
Canvas canvas;
// private Sprite[] sprites;
private final static int MAX_FPS = 40; //desired fps
private final static int FRAME_PERIOD = 1000 / MAX_FPS; // the frame period
public Game(Context context) {
super(context);
holder = getHolder();
holder.addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder holder) {
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
screenWidth = width;
screenHeight = height;
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
});
//====== not working
// Display display = ((Activity)context).getWindowManager().getDefaultDisplay();
// int sWidth = display.getWidth();
// int sHeight = display.getHeight();
//====== not working
// DisplayMetrics dm = new DisplayMetrics();
// ((Activity)context).getWindowManager().getDefaultDisplay().getMetrics(dm);
// int sWidth = dm.widthPixels;
// int sHeight = dm.heightPixels;
//====== not working
// screenHeight=canvas.getHeight();
// screenWidth=canvas.getWidth();
s=new Sprite(0, 0, BitmapFactory.decodeResource(this.getResources(), R.mipmap.back));
}
/**
* Start or resume the game.
*/
public void resume() {
isRunning = true;
gameThread = new Thread(this);
gameThread.start();
}
/**
* Pause the game loop
*/
public void pause() {
isRunning = false;
boolean retry = true;
while (retry) {
try {
gameThread.join();
retry = false;
} catch (InterruptedException e) {
// try again shutting down the thread
}
}
}
class Sprite {
int x;
int y;
int directionX = 1;
int directionY = 1;
int speed = 10;
int color = 0;
Bitmap image;
public Sprite(int x, int y) {
this.x = x;
this.y = y;
}
public Sprite(int x, int y, Bitmap image) {
this(x, y);
this.image = image;
}
public Sprite(int x, int y, Bitmap image, int color) {
this(x, y, image);
this.color = color;
}
}
protected void step()
{
//blablabla
}
protected void render(Canvas canvas) {
canvas.drawColor(Color.BLACK);
Paint p = new Paint();
canvas.drawBitmap(s.image,s.x,s.y,p);
}
#Override
public void run() {
while(isRunning) {
// We need to make sure that the surface is ready
if (! holder.getSurface().isValid()) {
continue;
}
long started = System.currentTimeMillis();
// update
step();
// draw
canvas = holder.lockCanvas();
if (canvas != null) {
render(canvas);
holder.unlockCanvasAndPost(canvas);
}
float deltaTime = (System.currentTimeMillis() - started);
int sleepTime = (int) (FRAME_PERIOD - deltaTime);
if (sleepTime > 0) {
try {
gameThread.sleep(sleepTime);
}
catch (InterruptedException e) {
}
}
while (sleepTime < 0) {
step();
sleepTime += FRAME_PERIOD;
}
}
}
}
This options doesn't work:
//====== not working
// Display display = ((Activity)context).getWindowManager().getDefaultDisplay();
// int sWidth = display.getWidth();
// int sHeight = display.getHeight();
//====== not working
// DisplayMetrics dm = new DisplayMetrics();
// ((Activity)context).getWindowManager().getDefaultDisplay().getMetrics(dm);
// int sWidth = dm.widthPixels;
// int sHeight = dm.heightPixels;
//====== not working
// screenHeight=canvas.getHeight();
// screenWidth=canvas.getWidth();
So how I can get the canvas or current screen size?
And set the Sprite.image to full screen ?
Try this for size in pixels,
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
Try this when you decode your bitmap.
final int width = context.getResources().getDisplayMetrics().widthPixels;
final int height = context.getResources().getDisplayMetrics().heightPixels;
BitmapFactory.Options options = new BitmapFactory.Options();
options.outHeight = height;
options.outWidth = width;
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher, options)
I am using set as wallpaper in my android app. But when I set image as wallpaper its zoom upto some extent on device. I want when I set image as wallpaper. This fit on every screen device. I am using DisplayMetrices but its not working perfect.
Code-
public class FullImageActivity extends Activity {
int position, width, height;
LinearLayout full;
Button btn;
Context context;
DisplayMetrics metrics;
public Integer[] mThumbId = {
R.drawable.kri1, R.drawable.kri2,
R.drawable.kri3, R.drawable.kri4,
R.drawable.kri5, R.drawable.kri6,
R.drawable.kri7, R.drawable.kri8,
R.drawable.kri9
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.full_image);
// get intent data
Intent i = getIntent();
// Selected image id
position = i.getExtras().getInt("id");
full = (LinearLayout) findViewById(R.id.full);
btn = (Button)findViewById(R.id.btn);
changeBackground();
metrics = this.getResources().getDisplayMetrics();
width = metrics.widthPixels;
height = metrics.heightPixels;
btn.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
WallpaperManager myWallpaperManager = WallpaperManager.getInstance(getApplicationContext());
try {
myWallpaperManager.suggestDesiredDimensions(width, height);
myWallpaperManager.setResource(mThumbId[position]);
} catch (IOException e) {
e.printStackTrace();
}
}});
ActivitySwipeDetector activitySwipeDetector = new ActivitySwipeDetector(this);
full.setOnTouchListener(activitySwipeDetector);
}
private void changeBackground(){
full.setBackgroundResource(mThumbId[position]);
}
public class ActivitySwipeDetector implements View.OnTouchListener {
static final String logTag = "ActivitySwipeDetector";
static final int MIN_DISTANCE = 100;
private float downX, upX;
Activity activity;
public ActivitySwipeDetector(Activity activity){
this.activity = activity;
}
public void onRightToLeftSwipe(){
Log.i(logTag, "RightToLeftSwipe!");
if(position < mThumbId.length - 1){
position++;
changeBackground();
}
}
public void onLeftToRightSwipe(){
Log.i(logTag, "LeftToRightSwipe!");
if(position > 0){
position--;
changeBackground();
}
}
public boolean onTouch(View v, MotionEvent event) {
switch(event.getAction()){
case MotionEvent.ACTION_DOWN: {
downX = event.getX();
return true;
}
case MotionEvent.ACTION_UP: {
upX = event.getX();
float deltaX = downX - upX;
// swipe horizontal?
if(Math.abs(deltaX) > MIN_DISTANCE){
// left or right
if(deltaX < 0) { this.onLeftToRightSwipe(); return true; }
if(deltaX > 0) { this.onRightToLeftSwipe(); return true; }
}
else {
Log.i(logTag, "Swipe was only " + Math.abs(deltaX) + " long, need at least " + MIN_DISTANCE);
return false; // We don't consume the event
}
return true;
}
}
return false;
}
}
}
Thanks in Advance.
Try this-
Bitmap bmap = BitmapFactory.decodeStream(getResources().openRawResource(mThumb[position]));
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int height = metrics.heightPixels;
int width = metrics.widthPixels;
Bitmap yourbitmap = Bitmap.createScaledBitmap(bmap, width, height, true);
WallpaperManager wallpaperManager = WallpaperManager.getInstance(this);
try {
wallpaperManager.setBitmap(yourbitmap);
} catch (IOException e) {
e.printStackTrace();
}
i'm using this library in my app
it works and it's easy
CropImage
it's open source so you can edit the library as you like
have fun
I guess you need a Image Scaling Algorithm that maintains the image Aspect Ratio,
Store the best image you have in your drawable folder and let this Algorithm scale down the best image to fit the device's Height & Width, maintaining the aspect ratio of the orignal Image.
Bitmap scaleDownLargeImageWithAspectRatio(Bitmap image)
{
int imaheVerticalAspectRatio,imageHorizontalAspectRatio;
float bestFitScalingFactor=0;
float percesionValue=(float) 0.2;
//getAspect Ratio of Image
int imageHeight=(int) (Math.ceil((double) image.getHeight()/100)*100);
int imageWidth=(int) (Math.ceil((double) image.getWidth()/100)*100);
int GCD=BigInteger.valueOf(imageHeight).gcd(BigInteger.valueOf(imageWidth)).intValue();
imaheVerticalAspectRatio=imageHeight/GCD;
imageHorizontalAspectRatio=imageWidth/GCD;
Log.i("scaleDownLargeImageWIthAspectRatio","Image Dimensions(W:H): "+imageWidth+":"+imageHeight);
Log.i("scaleDownLargeImageWIthAspectRatio","Image AspectRatio(W:H): "+imageHorizontalAspectRatio+":"+imaheVerticalAspectRatio);
//getContainer Dimensions
int displayWidth = getWindowManager().getDefaultDisplay().getWidth();
int displayHeight = getWindowManager().getDefaultDisplay().getHeight();
//I wanted to show the image to fit the entire device, as a best case. So my ccontainer dimensions were displayWidth & displayHeight. For your case, you will need to fetch container dimensions at run time or you can pass static values to these two parameters
int leftMargin = 0;
int rightMargin = 0;
int topMargin = 0;
int bottomMargin = 0;
int containerWidth = displayWidth - (leftMargin + rightMargin);
int containerHeight = displayHeight - (topMargin + bottomMargin);
Log.i("scaleDownLargeImageWIthAspectRatio","Container dimensions(W:H): "+containerWidth+":"+containerHeight);
//iterate to get bestFitScaleFactor per constraints
while((imageHorizontalAspectRatio*bestFitScalingFactor <= containerWidth) &&
(imaheVerticalAspectRatio*bestFitScalingFactor<= containerHeight))
{
bestFitScalingFactor+=percesionValue;
}
//return bestFit bitmap
int bestFitHeight=(int) (imaheVerticalAspectRatio*bestFitScalingFactor);
int bestFitWidth=(int) (imageHorizontalAspectRatio*bestFitScalingFactor);
Log.i("scaleDownLargeImageWIthAspectRatio","bestFitScalingFactor: "+bestFitScalingFactor);
Log.i("scaleDownLargeImageWIthAspectRatio","bestFitOutPutDimesions(W:H): "+bestFitWidth+":"+bestFitHeight);
image=Bitmap.createScaledBitmap(image, bestFitWidth,bestFitHeight, true);
//Position the bitmap centre of the container
int leftPadding=(containerWidth-image.getWidth())/2;
int topPadding=(containerHeight-image.getHeight())/2;
Bitmap backDrop=Bitmap.createBitmap(containerWidth, containerHeight, Bitmap.Config.RGB_565);
Canvas can = new Canvas(backDrop);
can.drawBitmap(image, leftPadding, topPadding, null);
return backDrop;
}
private void changeBackground()
{
Drawable inputDrawable = mThumbId[position];
Bitmap bitmap = ((BitmapDrawable)inputDrawable).getBitmap();
bitmap = scaleDownLargeImageWithAspectRatio(bitmap);
#SuppressWarnings("deprecation")
Drawable outDrawable=new BitmapDrawable(bitmap);
full.setBackground(outDrawable);
}
try this code to set image as Wallpaper
public void setWallpaper(final Bitmap bitmp)
{
int screenWidth=getWallpaperDesiredMinimumWidth();
int screenHeight=getWallpaperDesiredMinimumHeight();
try {
WallpaperManager wallpaperManager = WallpaperManager.getInstance(this);
Bitmap btm = getResizedBitmap(bitmp, screenHeight, screenWidth);
wallpaperManager.setBitmap(btm);
Toast toast=Toast.makeText(this, "Done", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.TOP|Gravity.CENTER, 0, 0);
toast.show();
} catch (IOException e) {
e.printStackTrace();
}
}
and
public 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;
/**
* create a matrix for the manipulation
*/
Matrix matrix = new Matrix();
/**
* resize the bit map
*/
matrix.postScale(scaleWidth, scaleHeight);
/**
* recreate the new Bitmap
*/
Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
return resizedBitmap;
}
EDIT :
You are required to just call the that function with desired bitmap
btn.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
setWallpaper(BitmapFactory.decodeResource(FullImageActivity.this.getResources(),
mThumbId[position]));
}});
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
I have an array of bitmap images loaded using harism curl page library found on https://github.com/harism/android_page_curl . I need to integrate zoom with gestures on each bitmap image. how can i achieve zoom with gestures. can anyone help me its a core issue i am facing for days.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lp = this;
util = new Utils();
if (getLastNonConfigurationInstance() != null) {
index = (Integer) getLastNonConfigurationInstance();
}
mCurlView = (CurlView) findViewById(R.id.curl);
mCurlView.setPageProvider(new PageProvider());
mCurlView.setSizeChangedObserver(new SizeChangedObserver());
mCurlView.setCurrentIndex(index);
// mCurlView.setBackgroundResource(R.drawable.icon);
imHome = (ImageView)findViewById(R.id.imHome);
imHome.setClickable(true);
imHome.setOnClickListener(lp);
btOne=(Button)findViewById(R.id.btOne);
btTwo=(Button)findViewById(R.id.btTwo);
btThree=(Button)findViewById(R.id.btThree);
btFour=(Button)findViewById(R.id.btFour);
llPageOne = (LinearLayout)findViewById(R.id.llPageOne);
btOne.setOnClickListener(this);
btTwo.setOnClickListener(this);
btThree.setOnClickListener(this);
btFour.setOnClickListener(this);
// This is something somewhat experimental. Before uncommenting next
// line, please see method comments in CurlView.
// mCurlView.setEnableTouchPressure(true);
}
#Override
public void onPause() {
super.onPause();
mCurlView.onPause();
}
#Override
public void onResume() {
super.onResume();
mCurlView.onResume();
}
#Override
public Object onRetainNonConfigurationInstance() {
return mCurlView.getCurrentIndex();
}
/**
* Bitmap provider.
*/
private class PageProvider implements CurlView.PageProvider {
// Bitmap resources.
private int[] mBitmapIds = {
R.drawable.luxury,R.drawable.luxury1,R.drawable.luxury_two
};
#Override
public int getPageCount() {
//return 5;
int pagesCount = 0;
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int wwidth = displaymetrics.widthPixels;
int hheight = displaymetrics.heightPixels;
if(wwidth > hheight){
if((mBitmapIds.length % 2) > 0)
pagesCount = (mBitmapIds.length / 2) + 1;
else
pagesCount = mBitmapIds.length / 2;
}else{
pagesCount = mBitmapIds.length;
}
System.out.println("page count "+pagesCount);
return pagesCount;
}
private Bitmap loadBitmap(int width, int height, int index) {
Bitmap b = Bitmap.createBitmap(width, height,
Bitmap.Config.ARGB_8888);
b.eraseColor(0xFFFFFFFF);
Canvas c = new Canvas(b);
Drawable d = getResources().getDrawable(mBitmapIds[index]);
System.out.println("canvas width: "+c.getWidth());
int margin = 3;//7
int border = 3;//2
Rect r = new Rect(margin, margin, width - margin, height - margin);
int imageWidth = r.width() - (border * 2);
int imageHeight = imageWidth * d.getIntrinsicHeight()
/ d.getIntrinsicWidth();
if (imageHeight > r.height() - (border * 2)) {
imageHeight = r.height() - (border * 2);
imageWidth = imageHeight * d.getIntrinsicWidth()
/ d.getIntrinsicHeight();
}
Log.d("TAG", String.valueOf(imageHeight));
if (lp.getWindow().getWindowManager().getDefaultDisplay()
.getOrientation() == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
// portrait mode
r.left += ((r.width() - imageWidth) / 2) - border;
r.right = r.left + imageWidth + border + border;
} else if (lp.getWindow().getWindowManager().getDefaultDisplay()
.getOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
// landscape
r.left += ((r.width() - imageWidth)) - border-122;
r.right = r.left + imageWidth + border + border+122;
}
r.top += ((r.height() - imageHeight) / 2) - border;
r.bottom = r.top + imageHeight + border + border;
Paint p = new Paint();
p.setColor(0xFFC0C0C0);
c.drawRect(r, p);
r.left += border;
r.right -= border;
r.top += border;
r.bottom -= border;
d.setBounds(r);
d.draw(c);
return b;
}
#Override
public void updatePage(CurlPage page, int width, int height, int index) {
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int wwidth = displaymetrics.widthPixels;
int hheight = displaymetrics.heightPixels;
if(wwidth > hheight){
System.out.println("index "+(index*2));
System.out.println("index2 "+(index*2)+1);
System.out.println("case landscape orientation...");
if (index >0){
front = loadBitmap(width, height, (index*2));
back = loadBitmap(width, height, (index*2)+1);
}else {
front = loadBitmap(width, height, (index));
back = loadBitmap(width, height, (index));
}
System.out.println( "MyActivity.onCreate debug message "+String.valueOf(index));
Matrix matrix = new Matrix();
matrix.preScale(-1.0f, 1.0f);
Bitmap mirroredBitmap = Bitmap.createBitmap(back, 0, 0, back.getWidth(), back.getHeight(), matrix, false);
page.setTexture(front, CurlPage.SIDE_FRONT);
page.setTexture(mirroredBitmap, CurlPage.SIDE_BACK);
// if (mCurlView.getCurrentIndex()==0){
//
// showPage1();
//
// }else {
//
// hidePage1();
// }
System.out.println("mCurlView.getCurrentIndex() "+mCurlView.getCurrentIndex());
}else{
System.out.println("case portrait orientation...");
Bitmap front = loadBitmap(width, height, index);
Bitmap back = loadBitmap(width, height, index);
System.out.println( "MyActivity.onCreate debug message "+String.valueOf(index));
page.setTexture(front, CurlPage.SIDE_FRONT);
page.setTexture(back, CurlPage.SIDE_BACK);
}
}
}
/**
* CurlView size changed observer.
*/
private class SizeChangedObserver implements CurlView.SizeChangedObserver {
#Override
public void onSizeChanged(int w, int h) {
if (w > h) {
mCurlView.setViewMode(CurlView.SHOW_TWO_PAGES);
mCurlView.setMargins(.000f, .000f, .000f, .000f);
} else {
mCurlView.setViewMode(CurlView.SHOW_ONE_PAGE);
mCurlView.setMargins(.005f, .005f, .00f, .00f);
}
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.btOne:
util.sendUri(this, "http://google.com/");
break;
case R.id.btTwo:
util.sendUri(this, "http://google.com/");
break;
case R.id.btThree:
util.sendUri(this, "http://google.com/");
break;
case R.id.btFour:
util.sendUri(this, "http://google.com/");
break;
case R.id.imHome:
mCurlView.setCurrentIndex(0);
System.out.println("home pressed");
mCurlView.onResume();
break;
}
}
public void showPage1(){
llPageOne.setVisibility(View.VISIBLE);
}
public void hidePage1(){
llPageOne.setVisibility(View.GONE);
}
// #Override
// public void onBackPressed() {
// // TODO Auto-generated method stub
//
// startActivity (new Intent (this,MyActivityMenuActivity.class));
// }
//
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.drop_list, menu);
return super.onCreateOptionsMenu(menu);
}
/**
* Override function onOptionsItemSelected(MenuItem item)
* Identify the item
* Call super class's onOptionsItemSelected(MenuItem item)
*/
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId()==R.id.menu_option_one){
startActivity (new Intent (this,ContactForm.class));
}
return super.onOptionsItemSelected(item);
}
Override onTouchEvent(MotionEvent event) and create an instance of ScaleGestureDetector.OnScaleGestureListener to detect zoom event. Than draw your bitmap according to zoom ratio
I have to add an ImageView programatically to an RelativeLayout such that it's 100dp to right of the center. I did this for a specific screen size and resolution, but I want it to work on any size of phone and desnity. What I tried for this is as follows :
CODE :
float xCord, yCord;
float xCenter, yCenter;
float radius;
float angle;
double x, y;
TextView tv;
RelativeLayout container;
ImageView view;
RelativeLayout.LayoutParams viewParams;
DisplayMetrics metrics ;
float density;
int dps,pxs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_circular_animation);
metrics = getApplicationContext().getResources().getDisplayMetrics();
float width = metrics.widthPixels;
float height = metrics.heightPixels;
tv = (TextView)findViewById(R.id.tv);
container = (RelativeLayout)findViewById(R.id.container);
xCenter = convertToDP(width)/2;
yCenter = convertToDP(height)/2;
radius = 100;
angle = 0;
x = xCenter + radius * Math.cos(angle * Math.PI / 180);
y = yCenter + radius * Math.sin(angle * Math.PI / 180);
view = new ImageView(this);
viewParams = new RelativeLayout.LayoutParams(50,50);
viewParams.leftMargin = (int) x;
viewParams.topMargin = (int) y;
view.setLayoutParams(viewParams);
view.setImageResource(R.drawable.square);
container.addView(view);
tv.setText(String.valueOf(xCenter) + " " + String.valueOf(yCenter));
}
public int convertToDP(float px) {
density = getApplicationContext().getResources().getDisplayMetrics().density;
dps = (int) ((px/density) + 0.5f);
return dps;
}
}
What I did is like, get the screen size and density and then divide it by 2 to get the center cords. Once i had the cords I used the formula to get the point on circumference of the circle at 0deg, but I am not getting the correct point. Any help would be great.
Try this:
public class sampleMediaPlayer extends Activity {
// Toast mToast;
// int i = 0;
// private boolean click;
// private Camera camera;
Handler mHandler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mainf);
}
#Override
protected void onResume() {
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
RelativeLayout rl = (RelativeLayout) findViewById(R.id.relativeLayout);
float r = DPtoPX(100);
float mScreenWidth = rl.getWidth() / 2; // DPtoPX(100);
float mScreenHeight = rl.getHeight() / 2;// DPtoPX(100);
for (int i = 0; i < 360; i = i + 30) {
addView(rl, (int) (mScreenWidth + r * Math.cos(i * Math.PI / 180F)),
(int) (mScreenHeight + (int) r * Math.sin(i * Math.PI / 180F)));
}
addView(rl, (int) mScreenWidth, (int) ((mScreenHeight)));
}
}, 50);
super.onResume();
}
void addView(ViewGroup rl, int x, int y) {
Log.i("NIMISH", x + " = " + y);
ImageView CenterImage = new ImageView(this);
RelativeLayout.LayoutParams viewParamsCenter = new RelativeLayout.LayoutParams(10, 10);
// viewParamsCenter.addRule(RelativeLayout.CENTER_IN_PARENT);
viewParamsCenter.leftMargin = x;
viewParamsCenter.topMargin = y;
CenterImage.setLayoutParams(viewParamsCenter);
CenterImage.setImageResource(R.drawable.ic_launcher);
rl.addView(CenterImage);
}
float DPtoPX(float dp) {
Resources r = getResources();
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics());
}
}
Explanation:
float width = metrics.widthPixels;
float height = metrics.heightPixels;
Returns the screen size including the TitleBar and StatusBar, but when you plot the image it calculated relative to that of the RelativeLayout. So if you draw image with height 'metrics.heightPixels' you will observe image to be out of screen. This phenomenon affects calculation of true center.
there are some other ways to calculate but each require that view to be plotted on screen. Hence any call after onResume()( used handler). As you can observe the function of calculating titlebar heights returns 0 when called form onResume().
private float Correction() {
Rect rectgle = new Rect();
Window window = getWindow();
window.getDecorView().getWindowVisibleDisplayFrame(rectgle);
int StatusBarHeight = rectgle.top;
int contentViewTop = window.findViewById(Window.ID_ANDROID_CONTENT).getTop();
int TitleBarHeight = contentViewTop - StatusBarHeight;
Log.i("NIMISH", "StatusBar Height= " + StatusBarHeight + " , TitleBar Height = " + TitleBarHeight);
return contentViewTop;
}
If you want user to input the X,Y coordinated you can alter the first program by
float mScreenWidth = DPtoPX(100);
float mScreenHeight = DPtoPX(100);
Doing so, It will plot the image with reference to the Relative layout, So you can remove the handler.