在发送到Wallpapermanager之前重新调整位图大小

时间:2013-10-05 09:38:24

标签: android bitmap wallpaper

我需要一些帮助才能在将位图发送到壁纸管理器之前调整位图的大小,以便当用户将其设置为壁纸时,它合理地适合,100%将是首选。

我正在使用壁纸管理器并从ImageView获取图像。

我遇到的问题是壁纸真的放大了。之前,当我从可绘制目录直接设置壁纸时,它看起来很好,你可以看到更多的图像,而不是它的1/4。从那以后我改变了我的代码,并且找到了更多有效的方法来获取我的图像和设置壁纸。

我查看了This link here,并试图找出如何实现答案,向您展示如何在将图像发送到壁纸管理器之前调整图像大小。

欢迎任何帮助,欢呼。

要提问的相关代码:

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

        }

全班同学:

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

2 个答案:

答案 0 :(得分:3)

如果你想让壁纸适合设备屏幕,那么你必须按照下面的步骤进行操作:

  1. 获取设备屏幕的高度和宽度
  2. 对位图图像进行采样
  3. 调整位图大小
  4. 在将位图设置为墙纸之前,回收先前的位图
  5. 代码:

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

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

    第4步:

    回收位图使用:

    bitmap.recycle();
    bitmap = null;
    

    调用resizeBitmap(context.getResources(), Measuredwidth, Measuredheight, THE_INPUTSTREAM_FROM_WHERE_YOU_ARE_DOWNLOADING_THE_IMAGE, FILELENGTH_FROM_THE_INPUTSTREAM);之类的函数。

    如果您从一个活动中调用该函数,则调用它:resizeBitmap(getResources(), Measuredwidth, Measuredheight, THE_INPUTSTREAM_FROM_WHERE_YOU_ARE_DOWNLOADING_THE_IMAGE, FILELENGTH_FROM_THE_INPUTSTREAM);

    该函数将返回调整后的位图,该位图将适合设备重构。 如果您已经将位图设置为墙纸,那么在将新位图设置为墙纸之前,请不要忘记回收位图。

答案 1 :(得分:1)

请查看功能并根据需要更改尺寸。感谢

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;

}

MyDevice在这里是一个单例类。您可以根据需要进行更改。 getdevicesize方法确定它是什么设备。

相关问题