2013-10-05 2 views
1

J'ai besoin d'aide pour redimensionner un bitmap avant de l'envoyer au gestionnaire de fonds d'écran de sorte que lorsque l'utilisateur le définit comme fond d'écran, il convient de 100%. J'utilise le gestionnaire de fond d'écran et j'obtiens l'image d'un ImageView.Redimensionnement d'un bitmap avant l'envoi à Wallpapermanager

Le problème que j'ai est le fond d'écran est vraiment zoomé. Avant, lorsque je définis le papier peint directement à partir du répertoire drawable, il semblait bien et vous pouvez voir beaucoup plus de l'image, pas 1/4 de celui-ci . J'ai changé mon code depuis et j'ai trouvé beaucoup plus d'un moyen efficace pour obtenir mes images et définir le fond d'écran.

J'ai regardé This link here et j'essaie de comprendre comment implémenter la réponse qui vous montre comment redimensionner l'image avant de l'envoyer au gestionnaire de papier peint.

Toute aide serait appréciée, à la vôtre.

Code relatif à la 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(); 
      } 

     } 

Mon toute la classe:

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); 
    } 
} 
} 

Répondre

3

si vous voulez adapter le fond d'écran avec l'écran Divice, vous devez suivre les étapes ci-dessous:

  1. obtenir la hauteur et la largeur de l'écran Divice
  2. exemple l'image bitmap
  3. redimensionner l'image bitmap
  4. avant de l'image bitmap en tant que papier peint, recycler le bitmap précédent

code:

étape 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(); 
} 

étape 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; 
} 

étape 4:

pour recycler l'utilisation de bitmap:

appelez la fonction comme resizeBitmap(context.getResources(), Measuredwidth, Measuredheight, THE_INPUTSTREAM_FROM_WHERE_YOU_ARE_DOWNLOADING_THE_IMAGE, FILELENGTH_FROM_THE_INPUTSTREAM);.

si vous appelez la fonction d'une activité l'appeler comme: resizeBitmap(getResources(), Measuredwidth, Measuredheight, THE_INPUTSTREAM_FROM_WHERE_YOU_ARE_DOWNLOADING_THE_IMAGE, FILELENGTH_FROM_THE_INPUTSTREAM);

la fonction retourne bitmap redimensionnée qui s'adaptera à la resulation de Divice. Si vous avez déjà défini un bitmap comme fond d'écran, n'oubliez pas de recycler le bitmap avant de définir un nouveau bitmap en tant que fond d'écran.

+0

Merci pour le commentaire détaillé, je vais essayer! :) – Jack

+0

@Jack: vous êtes le bienvenu. laissez-moi savoir si vous avez un autre problème :) – Shoshi

+0

Je reçois les images de l'Internet, Aussi, je reçois une erreur sur "getWindowManager" avec "La méthode getWindowManager() est indéfinie pour le nouveau type View.OnClickListener () {} "et j'obtiens une erreur sur" Measuredwidth "et" Measuredheight "avec" Measuredheight ne peut pas être résolu en une variable " – Jack

1

S'il vous plaît voir la fonction et changer la taille en fonction de vos besoins. Merci

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; 

} 

Où MyDevice est une classe singleton ici. Vous pouvez le changer comme vous voulez. La méthode getdevicesize détermine de quel périphérique il s'agit.

+0

Merci pour la réponse, je vais voir ce qui fonctionne le mieux! ;) – Jack

+0

Où pourrais-je mettre ceci dans mon code? Au clic? – Jack

Questions connexes