I wrote a simple application that sets the wallpaper on the device. I can't achieve one effect. I wish the picture automatically centrated horizontally. This means that the center of the image was on the most central desktop of Luncher app.
The picture at the bottom shows how it looks now:
Effect that I want to achieve:
And the image itself:
I tried to use the code from this question, however, did not achieve the desired effect.
My code:
public class SystemWallpaperHelper {
private Context context;
private ImageLoader imageLoader;
private DisplayImageOptions imageLoaderOptions;
public SystemWallpaperHelper(Context context){
this.context = context;
setImageLoaderOptions();
}
private void setImageLoaderOptions() {
final int width = SharedHelper.getDeviceWidth(context) << 1 ; // best wallpaper width is twice screen width
imageLoaderOptions = new DisplayImageOptions.Builder()
.imageScaleType(ImageScaleType.NONE)
.cacheInMemory(false)
.cacheOnDisk(false)
.postProcessor(new BitmapProcessor() {
#Override
public Bitmap process(Bitmap bmp) {
float scale = (float) width / bmp.getWidth() ;
int height = (int) (scale * bmp.getHeight());
return Bitmap.createScaledBitmap(bmp, width, height, false);
}
})
.build();
imageLoader = ImageLoader.getInstance();
}
public void setDeviceWallpaper(Wallpaper wallpaper){
imageLoader.loadImage(wallpaper.getSrcUrl(), imageLoaderOptions, new SimpleImageLoadingListener(){
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage)
{
WallpaperManager wallpaperManager = WallpaperManager.getInstance(context);
try {
wallpaperManager.setBitmap(loadedImage);
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
After several attempts, I managed to achieve the desired effect.
public class SystemWallpaperHelper {
private Context context;
private ImageLoader imageLoader;
private DisplayImageOptions imageLoaderOptions;
private WallpaperManager wallpaperManager;
public SystemWallpaperHelper(Context context) {
this.context = context;
setImageLoaderOptions();
wallpaperManager = WallpaperManager.getInstance(context);
}
private void setImageLoaderOptions() {
imageLoaderOptions = new DisplayImageOptions.Builder()
.imageScaleType(ImageScaleType.NONE)
.cacheInMemory(false)
.cacheOnDisk(false)
.postProcessor(new BitmapProcessor() {
#Override
public Bitmap process(Bitmap bmp) {
return centerCropWallpaper(bmp, wallpaperManager.getDesiredMinimumWidth(), wallpaperManager.getDesiredMinimumHeight());
}
})
.build();
imageLoader = ImageLoader.getInstance();
}
private Bitmap centerCropWallpaper(Bitmap wallpaper, int desiredWidth, int desiredHeight){
float scale = (float) desiredHeight / wallpaper.getHeight();
int scaledWidth = (int) (scale * wallpaper.getWidth());
int deviceWidth = SharedHelper.getDeviceWidth(context);
int imageCenterWidth = scaledWidth /2;
int widthToCut = imageCenterWidth - deviceWidth / 2;
int leftWidth = scaledWidth - widthToCut;
Bitmap scaledWallpaper = Bitmap.createScaledBitmap(wallpaper, scaledWidth, desiredHeight, false);
Bitmap croppedWallpaper = Bitmap.createBitmap(
scaledWallpaper,
widthToCut,
0,
leftWidth,
desiredHeight
);
return croppedWallpaper;
}
public void setDeviceWallpaper(final Wallpaper wallpaper, final boolean adjusted) {
imageLoader.loadImage(wallpaper.getSrcUrl(), imageLoaderOptions, new SimpleImageLoadingListener() {
#TargetApi(Build.VERSION_CODES.KITKAT)
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
if (adjusted) {
wallpaperManager.getCropAndSetWallpaperIntent(SharedHelper.getImageUriForBitmap(context, loadedImage));
} else {
try {
int width = wallpaperManager.getDesiredMinimumWidth();
int height = wallpaperManager.getDesiredMinimumHeight();
int bitWidth = loadedImage.getWidth();
wallpaperManager.setBitmap(loadedImage);
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
}
}
Here is a more generic version, that can be pasted in any java android class. As an addition, it is not dependend on the display orientation.
public static void setWallpaper(Context context, BitmapDrawable wallpaper) {
try {
WallpaperManager wallpaperManager = WallpaperManager.getInstance(context);
if(wallpaper != null) {
Bitmap bmp = wallpaper.getBitmap();
DisplayMetrics metrics = new DisplayMetrics();
WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
windowManager.getDefaultDisplay().getMetrics(metrics);
int height = metrics.heightPixels;
int width = metrics.widthPixels;
wallpaperManager.setWallpaperOffsetSteps(1, 1);
wallpaperManager.suggestDesiredDimensions(width, height);
Bitmap bitmap = centerCropWallpaper(context, bmp, Math.min(wallpaperManager.getDesiredMinimumWidth(), wallpaperManager.getDesiredMinimumHeight()));
wallpaperManager.setBitmap(bitmap);
} else {
Log.e(TAG, "wallpaper could not be set.");
}
} catch (Exception ex) {
Log.e(TAG, "error setting wallpaper. " + ex.getMessage(), ex);
}
}
private static Bitmap centerCropWallpaper(Context context, Bitmap wallpaper, int desiredHeight){
float scale = (float) desiredHeight / wallpaper.getHeight();
int scaledWidth = (int) (scale * wallpaper.getWidth());
DisplayMetrics metrics = new DisplayMetrics();
WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
windowManager.getDefaultDisplay().getMetrics(metrics);
int deviceWidth = metrics.widthPixels;
int imageCenterWidth = scaledWidth /2;
int widthToCut = imageCenterWidth - deviceWidth / 2;
int leftWidth = scaledWidth - widthToCut;
Bitmap scaledWallpaper = Bitmap.createScaledBitmap(wallpaper, scaledWidth, desiredHeight, false);
return Bitmap.createBitmap(scaledWallpaper, widthToCut, 0, leftWidth, desiredHeight);
}
Related
I am creating a moving animation for my Card Game, for this i have created a custom surface view, while calling invalidate method inside my Surface View i am getting following exception
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
My code:
Thread Class
class MySurfaceViewThread:BaseThread
{
private MySurfaceView mysurfaceview;
private ISurfaceHolder myThreadSurfaceHolder;
bool running;
public MySurfaceViewThread(ISurfaceHolder paramSurfaceHolder, MySurfaceView paramSurfaceView)
{
mysurfaceview = paramSurfaceView;
myThreadSurfaceHolder = paramSurfaceHolder;
}
public override void RunThread()
{
Canvas c;
while (running)
{
c = null;
try
{
c = myThreadSurfaceHolder.LockCanvas(null);
mysurfaceview.Render(c);
mysurfaceview.PostInvalidate();
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.ToString());
}
finally
{
if (c != null)
{
myThreadSurfaceHolder.UnlockCanvasAndPost(c);
}
// running = false;
}
}
}
public override void SetRunning(bool paramBoolean)
{
running = paramBoolean;
}
}
Surface View Class
class MySurfaceView : SurfaceView, ISurfaceHolderCallback
{
ISurfaceHolder holder;
MySurfaceViewThread thread;
Context context;
Deck DealtDeck;
DisplayMetrics metrics;
int Screen_Center_X;
int Screen_Center_Y;
int Screen_Width;
int Screen_Height;
int Screen_Top_Middle_X;
int Screen_Top_Middle_Y;
int Screen_Bottom_Middle_X;
int Screen_Bottom_Middle_Y;
float density;
int Card_Width;
int Card_Height;
int Down_Card_Gap;
Deck DiscardedDeck;
Deck MainPlayer;
int localdownanimationvalue=0;
Bitmap localimage;
Bitmap rotatedimage;
Cards localcard;
public MySurfaceView(Context context):base(context)
{
this.context = context;
metrics = Resources.DisplayMetrics;
SetWillNotDraw(false);
Init();
}
public MySurfaceView(Context context, IAttributeSet attrs):base(context, attrs)
{
this.context=context;
metrics = Resources.DisplayMetrics;
SetWillNotDraw(false);
Init();
}
private void Init()
{
Console.WriteLine("Init method start");
// SurfaceView surfaceview = this;
holder = Holder;
holder.AddCallback(this);
this.thread = new MySurfaceViewThread(holder,this);
Focusable=true;
}
public void SurfaceChanged(ISurfaceHolder holder, [GeneratedEnum] Format format, int width, int height)
{
//throw new NotImplementedException();
}
public void SurfaceCreated(ISurfaceHolder holder)
{
this.thread.SetRunning(true);
this.thread.Start();
Initializevariable();
AllocatedCardList();
SetWillNotDraw(false);
}
private void Initializevariable()
{
Screen_Width = metrics.WidthPixels;
Screen_Height = metrics.HeightPixels;
density = metrics.Density;
Card_Width = (int)(125.0F * density);
Card_Height = (int)(93.0F * density);
Screen_Center_X = Screen_Width / 2;
Screen_Center_Y = Screen_Height / 2;
Screen_Top_Middle_X = Screen_Center_X - Card_Width;
Screen_Top_Middle_Y = Screen_Center_Y - Card_Height;
Screen_Bottom_Middle_X = Screen_Center_X - Card_Width/2;
Screen_Bottom_Middle_Y = Screen_Height - Card_Height;
DealtDeck = new Deck();
MainPlayer = new Deck();
// FaceDownDeck = new Deck(Screen_Center_X - Card_Width/2, Screen_Center_Y- Card_Height/2);
}
public void SurfaceDestroyed(ISurfaceHolder holder)
{
bool retry = true;
this.thread.SetRunning(false);
while(retry)
{
thread.Join();
retry = false;
}
}
void AllocatedCardList()
{
Cards localcard;
//Allocate all cards to dealtdeck first
for (int i = 1; i <= 13; i++)
{
for (int j = 1; j <= 4; j++)
{
DealtDeck.Add(new Cards((Cards.Rank)i, (Cards.SuitType)j, true, (Screen_Center_X - Card_Width / 2), (Screen_Center_Y - Card_Height / 2)));
}
}
//Allocate to bottom player starting card should be bottom-center
localcard = DealtDeck.RemoveCard();
localcard.current_X = Screen_Bottom_Middle_X;
localcard.current_Y = Screen_Bottom_Middle_Y;
MainPlayer.Add(localcard);
}
public void Render(Canvas paramCanvas)
{
try
{
//
localcard = DealtDeck.getCard();
if (localdownanimationvalue <= Screen_Height)
{
paramCanvas.DrawColor(Android.Graphics.Color.Transparent, PorterDuff.Mode.Clear);
localimage = DecodeSampledBitmapFromResource(Resources, localcard.GetImageId(context), Card_Width, Card_Height);
rotatedimage = RotateBitmap(localimage, 180);
paramCanvas.DrawBitmap(rotatedimage, Screen_Center_X, localdownanimationvalue, null);
Updatedowncardvalue();
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.ToString());
}
}
protected override void OnDraw(Canvas paramCanvas)
{
}
private void Updatedowncardvalue()
{
const int updatevalue = 50;
if (localdownanimationvalue + updatevalue > Screen_Height)
localdownanimationvalue = Screen_Height;
else
localdownanimationvalue = localdownanimationvalue + updatevalue;
Invalidate();
}
private Bitmap DecodeSampledBitmapFromResource(Resources resources, int cardid, int card_Width, int card_Height)
{
BitmapFactory.Options options = new BitmapFactory.Options
{
InJustDecodeBounds = true
};
Bitmap image = BitmapFactory.DecodeResource(resources, cardid,options);
options.InSampleSize = CalculateInSampleSize(options, card_Width, card_Height);
options.InJustDecodeBounds = false;
return BitmapFactory.DecodeResource(resources, cardid, options);
}
private int CalculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight)
{
// Raw height and width of image
int width = options.OutWidth;
int height = options.OutHeight;
int samplesize = 1;
if(height > reqHeight || width > reqWidth)
{
// Calculate ratios of height and width to requested height and width
int heightratio = (int)Math.Round((double)height / reqHeight);
int widthratio = (int)Math.Round((double)width / reqWidth);
// Choose the smallest ratio as inSampleSize value, this will guarantee
// a final image with both dimensions larger than or equal to the
// requested height and width.
samplesize = heightratio < widthratio ? widthratio : heightratio;
}
return samplesize;
}
private Bitmap RotateBitmap(Bitmap localimage, float angle)
{
Matrix matrix = new Matrix();
matrix.PostRotate(angle);
Bitmap resized= Bitmap.CreateBitmap(localimage, 0, 0, localimage.Width, localimage.Height, matrix, true);
localimage.Recycle();
return resized;
}
}
Stacktrace:
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6462)
at android.view.ViewRootImpl.invalidateChildInParent(ViewRootImpl.java:932)
at android.view.ViewGroup.invalidateChild(ViewGroup.java:4692)
at android.view.View.invalidateInternal(View.java:11806)
at android.view.View.invalidate(View.java:11770)
at android.view.View.invalidate(View.java:11754)
Only the original thread that created a view hierarchy can touch its views.
You need to use RunOnUiThread from within your thread code whenever you update your views:
RunOnUiThread (() => {
someView.SomeProperty = "SO";
});
re: https://developer.android.com/reference/android/app/Activity.html#runOnUiThread(java.lang.Runnable)
Have some problem with wallpapers. This problem appear on some old and low-end devices. I'm trying to install wallpaper which may not scrolls(with device proportions) and they are normally installed. But after some time (2 or 3 days) wallpapers is scaling in 2 times(looks no pretty) and begin scrolling.
Here is part of code that install wallpapers:
public class WallpaperInstaller {
private Context mContext;
private CropImageView cropImageView;
private ImageLoader loader;
private boolean isCropped;
public WallpaperInstaller(Context context, final CropImageView civ, ImageLoader imageLoader) {
this.mContext = context;
this.cropImageView = civ;
this.loader = imageLoader;
this.isCropped = true;
}
public WallpaperInstaller(Context context, ImageLoader imageLoader) {
this.mContext = context;
this.loader = imageLoader;
this.isCropped = false;
}
public Thread setWallpaper(final String URL){
Thread setWallpaperThread = new Thread(new Runnable() {
#Override
public void run() {
WallpaperManager wallpaperManager = WallpaperManager.getInstance(mContext);
try {
Bitmap croppedBitmap;
if(isCropped){
int scale = 1;
RectF rect = cropImageView.getActualCropRect();
int cropX = (int) rect.left * scale;
int cropY = (int) rect.top * scale;
int cropW = (int) rect.width() * scale;
int cropH = (int) rect.height() * scale;
croppedBitmap = Bitmap.createBitmap(loader.loadImageSync(URL), cropX, cropY, cropW, cropH);
} else {
try{
croppedBitmap = Bitmap.createBitmap(loader.loadImageSync(URL));
} catch (NullPointerException e){
loader.init(ImageLoaderConfiguration.createDefault(mContext));
croppedBitmap = Bitmap.createBitmap(loader.loadImageSync(URL));
}
}
boolean isScrollable = croppedBitmap.getWidth() > croppedBitmap.getHeight();
if(isScrollable){
wallpaperManager.setWallpaperOffsetSteps(-1, -1);
wallpaperManager.suggestDesiredDimensions(getWidth(croppedBitmap), getDisplay().getHeight());
wallpaperManager.setBitmap(Bitmap.createScaledBitmap(croppedBitmap, getWidth(croppedBitmap), getDisplay().getHeight(), false));
} else{
wallpaperManager.setWallpaperOffsetSteps(1, 1);
wallpaperManager.suggestDesiredDimensions(getDisplay().getWidth(), getDisplay().getHeight());
wallpaperManager.setBitmap(Bitmap.createScaledBitmap(croppedBitmap, getDisplay().getWidth(), getDisplay().getHeight(), false));
}
} catch (IOException e) {
e.printStackTrace();
}
}
private int getWidth(Bitmap bitmap){
return (int)((float)getDisplay().getHeight()*(float)bitmap.getWidth()/(float)bitmap.getHeight());
}
private Display getDisplay(){
WindowManager windowManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
return windowManager.getDefaultDisplay();
}
});
return setWallpaperThread;
}
}
Thanks for your help.
Try adding next lines:
wallpaperManager.forgetLoadedWallpaper();
wallpaperManager.clear();
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'm new in Android Programming I'm Trying to make slideshow animated live wallpaper and all ok but the problem is when I set the wallpaper the scale of image is stretched to screen I want it to scale to all the phone screens and when swipe the wallpaper get the right part of image I Want Advice about this problem.
my code is :
public class CustomWallpaper extends WallpaperService {
#Override
public Engine onCreateEngine() {
return new WallpaperEngine();
}
class WallpaperEngine extends Engine {
//Duration between slides in milliseconds
private final int SLIDE_DURATION = 8;
private int[] mImagesArray;
private int mImagesArrayIndex = 0;
private Thread mDrawWallpaper;
private String mImageScale = "Fit to screen";
private CustomWallpaperHelper customWallpaperHelper;
public WallpaperEngine() {
customWallpaperHelper = new CustomWallpaperHelper(getApplicationContext(), getResources());
mImagesArray = new int[] {R.drawable.image_1,R.drawable.image_2,R.drawable.image_3,R.drawable.image_4,R.drawable.image_5,R.drawable.image_6,R.drawable.image_7,R.drawable.image_8,R.drawable.image_9,R.drawable.image_10,R.drawable.image_11,R.drawable.image_12,R.drawable.image_13,R.drawable.image_14,R.drawable.image_15,R.drawable.image_16,R.drawable.image_17,R.drawable.image_18,R.drawable.image_19,R.drawable.image_20,R.drawable.image_21,R.drawable.image_22,R.drawable.image_23,R.drawable.image_24,R.drawable.image_25,R.drawable.image_26,R.drawable.image_27,R.drawable.image_28,R.drawable.image_29,R.drawable.image_30,R.drawable.image_31,R.drawable.image_32,R.drawable.image_33,R.drawable.image_34,R.drawable.image_35,R.drawable.image_36,R.drawable.image_37,R.drawable.image_38,R.drawable.image_39,R.drawable.image_40,R.drawable.image_41};
mDrawWallpaper = new Thread(new Runnable() {
#Override
public void run() {
try {
while (true) {
drawFrame();
incrementCounter();
Thread.sleep(SLIDE_DURATION);
}
} catch (Exception e) {
//
}
}
});
mDrawWallpaper.start();
}
private void incrementCounter() {
mImagesArrayIndex++;
if (mImagesArrayIndex >= mImagesArray.length) {
mImagesArrayIndex = 0;
}
}
private void drawFrame() {
final SurfaceHolder holder = getSurfaceHolder();
Canvas canvas = null;
try {
canvas = holder.lockCanvas();
if (canvas != null) {
drawImage(canvas);
}
} finally {
if (canvas != null) {
holder.unlockCanvasAndPost(canvas);
}
}
}
private void drawImage(Canvas canvas) {
//Get the image and resize it
Bitmap image = BitmapFactory.decodeResource(getResources(),
mImagesArray[mImagesArrayIndex]);
//Draw background
customWallpaperHelper.setBackground(canvas);
//Scale the canvas
PointF mScale = customWallpaperHelper.getCanvasScale(mImageScale, image.getWidth(), image.getHeight());
canvas.scale(mScale.x, mScale.y);
//Draw the image on screen
Point mPos = customWallpaperHelper.getImagePos(mScale, image.getWidth(), image.getHeight());
canvas.drawBitmap(image, mPos.x, mPos.y, null);
}
}
}
and the other class is:
public class CustomWallpaperHelper {
public final static String IMAGE_SCALE_STRETCH_TO_SCREEN = "Stretch to screen";
public final static String IMAGE_SCALE_FIT_TO_SCREEN = "Fit to screen";
private Context mContext;
private Resources mResources;
private Point screenSize = new Point();
private Bitmap bgImageScaled;
private Point bgImagePos = new Point(0, 0);
public CustomWallpaperHelper(Context mContext, Resources mResources) {
this.mContext = mContext;
this.mResources = mResources;
WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
screenSize.x = display.getWidth();
screenSize.y = display.getHeight();
;
}
private void scaleBackground() {
String imageScale = "Stretch to screen";
Bitmap bgImage = null;
if (imageScale.equals(IMAGE_SCALE_STRETCH_TO_SCREEN)) {
bgImagePos = new Point(0, 0);
bgImageScaled = Bitmap.createScaledBitmap(bgImage, screenSize.x, screenSize.y, true);
}
}
public void setBackground(Canvas canvas) {
if (bgImageScaled != null) {
canvas.drawBitmap(bgImageScaled, bgImagePos.x, bgImagePos.y, null);
} else {
canvas.drawColor(0xff000000);
}
}
public int getScreenWidth() {
return screenSize.x;
}
public int getScreenHeight() {
return screenSize.y;
}
public Point getImagePos(PointF canvasScale, int imageWidth, int imageHeight) {
Point imagePos = new Point();
imagePos.x = (int) (screenSize.x - (imageWidth * canvasScale.x)) / 2;
imagePos.y = (int) (screenSize.y - (imageHeight * canvasScale.y)) / 2;
return imagePos;
}
public PointF getCanvasScale(String imageScale, int imageWidth, int imageHeight) {
PointF canvasScale = new PointF(1f, 1f);
if (imageScale.equals(IMAGE_SCALE_STRETCH_TO_SCREEN)) {
canvasScale.x = getScreenWidth() / (1f * imageWidth);
canvasScale.y = getScreenHeight() / (1f * imageHeight);
} else {
boolean tooWide = false;
boolean tooTall = false;
if (getScreenWidth() < imageWidth) {
tooWide = true;
}
if (getScreenHeight() < imageHeight) {
tooTall = true;
}
if (tooWide && tooTall) {
int x = imageWidth / getScreenWidth();
int y = imageHeight / getScreenHeight();
if (x > y) {
canvasScale.x = getScreenWidth() / (1f * imageWidth);
canvasScale.y = 1;
} else {
canvasScale.x = 1;
canvasScale.y = getScreenHeight() / (1f * imageHeight);
}
} else if (tooWide) {
canvasScale.x = getScreenWidth() / (1f * imageWidth);
canvasScale.y = 1;
} else if (tooTall) {
canvasScale.x = 1;
canvasScale.y = getScreenHeight() / (1f * imageHeight);
}
}
return canvasScale;
}
}
I want Advice for this problem.
Thanks.
no need to do anything just Replace your below method with my code.
private void drawImage(Canvas canvas)
{
Bitmap image = BitmapFactory.decodeResource(getResources(),
mImagesArray[mImagesArrayIndex]);
Bitmap b=Bitmap.createScaledBitmap(image, canvas.getWidth(), canvas.getHeight(), true);
canvas.drawBitmap(b, 0,0, null);
}
I would suggest that you crop the images instead of resizing them. Something like:
Rect r = new Rect(left, top, right, bottom);
Bitmap croppedImage = null;
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD_MR1){
InputStream in = mContentResolver.openInputStream(mSaveUri);
BitmapRegionDecoder decoder = BitmapRegionDecoder.newInstance(in, false);
croppedImage = decoder.decodeRegion(r, null);
} else {
final int width = r.width();
final int height = r.height();
croppedImage = Bitmap.createBitmap(mBitmap, r.left, r.top, width, height);
croppedImage.setDensity(croppedImage.getDensity() * mOutputX / width);
}
return croppedImage;
Hope this helps...
I am needing some help with resizing a bitmap before sending it to the wallpaper manager so that when the user sets it as their wallpaper, it fits reasonably, 100% would be preferred.
I am using wallpaper manager and am getting the image from an ImageView.
The issue I am having is the wallpaper is really zoomed in. Before, when I set the wallpaper straight from the drawable directory, it looked fine and you could see a lot more of the image, not 1/4 of it. I have changed my code up since then and have found a lot more of an effective way to get my images and set the wallpaper.
I have looked at This link here and am trying to figure out how to implement the answer that shows you how to resize the image before sending it to the wallpaper manager.
Any help would be appreciated, cheers.
Relative code to question:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.image_detail_fragment,
container, false);
int Measuredwidth = 0;
int Measuredheight = 0;
WindowManager w = getActivity().getWindowManager();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
w.getDefaultDisplay().getSize(Size);
Measuredwidth = Size.x;
Measuredheight = Size.y;
} else {
Display d = w.getDefaultDisplay();
Measuredwidth = d.getWidth();
Measuredheight = d.getHeight();
}
mImageView = (RecyclingImageView) v.findViewById(R.id.imageView);
mImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
BitmapDrawable drawable = (BitmapDrawable) mImageView
.getDrawable();
Bitmap bitmap = drawable.getBitmap();
WallpaperManager myWallpaperManager = WallpaperManager
.getInstance(getActivity());
try {
myWallpaperManager.setBitmap(bitmap);
;
Toast.makeText(getActivity(),
"Wallpaper Successfully Set!", Toast.LENGTH_LONG)
.show();
} catch (IOException e) {
Toast.makeText(getActivity(), "Error Setting Wallpaper",
Toast.LENGTH_LONG).show();
}
}
My whole class:
public class ImageDetailFragment extends Fragment {
private static final String IMAGE_DATA_EXTRA = "extra_image_data";
private static final Point Size = null;
private String mImageUrl;
private RecyclingImageView mImageView;
private ImageFetcher mImageFetcher;
public static ImageDetailFragment newInstance(String imageUrl) {
final ImageDetailFragment f = new ImageDetailFragment();
final Bundle args = new Bundle();
args.putString(IMAGE_DATA_EXTRA, imageUrl);
f.setArguments(args);
return f;
}
public ImageDetailFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mImageUrl = getArguments() != null ? getArguments().getString(
IMAGE_DATA_EXTRA) : null;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.image_detail_fragment,
container, false);
int Measuredwidth = 0;
int Measuredheight = 0;
WindowManager w = getActivity().getWindowManager();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
w.getDefaultDisplay().getSize(Size);
Measuredwidth = Size.x;
Measuredheight = Size.y;
} else {
Display d = w.getDefaultDisplay();
Measuredwidth = d.getWidth();
Measuredheight = d.getHeight();
}
mImageView = (RecyclingImageView) v.findViewById(R.id.imageView);
mImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
BitmapDrawable drawable = (BitmapDrawable) mImageView
.getDrawable();
Bitmap bitmap = drawable.getBitmap();
WallpaperManager myWallpaperManager = WallpaperManager
.getInstance(getActivity());
try {
myWallpaperManager.setBitmap(bitmap);
;
Toast.makeText(getActivity(),
"Wallpaper Successfully Set!", Toast.LENGTH_LONG)
.show();
} catch (IOException e) {
Toast.makeText(getActivity(), "Error Setting Wallpaper",
Toast.LENGTH_LONG).show();
}
}
});
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (Batmanark.class.isInstance(getActivity())) {
mImageFetcher = ((Batmanark) getActivity()).getImageFetcher();
mImageFetcher.loadImage(mImageUrl, mImageView);
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (mImageView != null) {
// Cancel any pending image work
ImageWorker.cancelWork(mImageView);
mImageView.setImageDrawable(null);
}
}
}
if you want to fit the wallpaper with the divice screen, then you have to follow the steps bellow:
get the height and width of the divice screen
sample the bitmap image
resize the bitmap
before setting the bitmap as wallpaper, recycle the previous bitmap
code:
step 1:
int Measuredwidth = 0;
int Measuredheight = 0;
Point size = new Point();
// if you are doing it from an activity
WindowManager w = getWindowManager();
// otherwise use this
WindowManager w = context.getWindowManager();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
w.getDefaultDisplay().getSize(size);
Measuredwidth = size.x;
Measuredheight = size.y;
} else {
Display d = w.getDefaultDisplay();
Measuredwidth = d.getWidth();
Measuredheight = d.getHeight();
}
step 2+3:
public Bitmap resizeBitmap(Resources res, int reqWidth, int reqHeight,
InputStream inputStream, int fileLength) {
Bitmap bitmap = null;
InputStream in = null;
InputStream in2 = null;
InputStream in3 = null;
try {
in3 = inputStream;
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayOutputStream out2 = new ByteArrayOutputStream();
copy(in3,out,fileLength);
out2 = out;
in2 = new ByteArrayInputStream(out.toByteArray());
in = new ByteArrayInputStream(out2.toByteArray());
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(in, null, options);
if(options.outHeight == -1 || options.outWidth == 1 || options.outMimeType == null){
return null;
}
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
options.inJustDecodeBounds = false;
bitmap = BitmapFactory.decodeStream(in2, null, options);
if(bitmap != null){
bitmap = Bitmap.createScaledBitmap(bitmap, reqWidth, reqHeight, false);
}
in.close();
in2.close();
in3.close();
} catch (IOException e1) {
e1.printStackTrace();
}
return bitmap;
}
public int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
// Calculate ratios of height and width to requested height and width
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// Choose the smallest ratio as inSampleSize value, this will guarantee a final image
// with both dimensions larger than or equal to the requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
// This offers some additional logic in case the image has a strange
// aspect ratio. For example, a panorama may have a much larger
// width than height. In these cases the total pixels might still
// end up being too large to fit comfortably in memory, so we should
// be more aggressive with sample down the image (=larger inSampleSize).
final float totalPixels = width * height;
// Anything more than 2x the requested pixels we'll sample down further
final float totalReqPixelsCap = reqWidth * reqHeight * 2;
while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
inSampleSize++;
}
}
return inSampleSize;
}
public int copy(InputStream input, OutputStream output, int fileLength) throws IOException{
byte[] buffer = new byte[8*1024];
int count = 0;
int n = 0;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
count += n;
publishProgress((int) (count * 100 / fileLength));
}
return count;
}
step 4:
to recycle the bitmap use:
bitmap.recycle();
bitmap = null;
call the function like resizeBitmap(context.getResources(), Measuredwidth, Measuredheight,
THE_INPUTSTREAM_FROM_WHERE_YOU_ARE_DOWNLOADING_THE_IMAGE,
FILELENGTH_FROM_THE_INPUTSTREAM);.
if you are calling the function from an activity the call it like: resizeBitmap(getResources(), Measuredwidth, Measuredheight,
THE_INPUTSTREAM_FROM_WHERE_YOU_ARE_DOWNLOADING_THE_IMAGE, FILELENGTH_FROM_THE_INPUTSTREAM);
the function will return resized bitmap which will fit with the divice resulation.
if you have already setted a bitmap as wallpaper, then don't forget to recycle the bitmap before you set a new bitmap as wallpaper.
Please see the function and change the size according to your need. Thanks
public Bitmap createScaledImage(Bitmap bit) {
Bitmap bitmapOrg = bit;
int width = bitmapOrg.getWidth();
int height = bitmapOrg.getHeight();
int newWidth = 0, newHeight = 0;
if (MyDevice.getInstance().getDeviceSize().equals("XLARGE")) {
MyDevice.getInstance().SCALE = 65;
newWidth = 65;
newHeight = 65;
} else if (MyDevice.getInstance().getDeviceSize().equals("LARGE")) {
MyDevice.getInstance().SCALE = 60;
newWidth = 60;
newHeight = 60;
}
else if (MyDevice.getInstance().getDeviceSize().equals("NORMAL")) {
MyDevice.getInstance().SCALE = 50;
newWidth = 50;
newHeight = 50;
if (h > 800) {
MyDevice.getInstance().SCALE = 60;
newWidth = 60;
newHeight = 60;
}
} else if (MyDevice.getInstance().getDeviceSize().equals("SMALL")) {
MyDevice.getInstance().SCALE = 30;
newWidth = 30;
newHeight = 30;
}
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
Matrix matrix = new Matrix();
// resize the bit map
matrix.postScale(scaleWidth, scaleHeight);
// recreate the new Bitmap
Bitmap resizedBitmap = Bitmap.createBitmap(bitmapOrg, 0, 0, width,
height, matrix, true);
return resizedBitmap;
}
Where MyDevice is a singleton class here. You can change it as you want. getdevicesize method determines what device it is.