Android开发中那些有用的方法

来源:互联网 发布:arctime 字幕制作软件 编辑:程序博客网 时间:2024/05/18 02:08

本文用于汇总开发中实现的一些极为有用的方法,此文持续更新,希望对大家的开发有所帮助。

获取屏幕宽度

    public static int getScreenWidth(Context context) {        WindowManager manager = (WindowManager) context                .getSystemService(Context.WINDOW_SERVICE);        Display display = manager.getDefaultDisplay();        return display.getWidth();    }

dp值转px值

    public static int dp2px(Context context, final int dpValue) {        DisplayMetrics displayMetrics;        displayMetrics = context.getResources().getDisplayMetrics();        return (int)(displayMetrics.density * dpValue);    }

获得listView的指定position的itemView

    public static View getViewByPosition(int pos, ListView listView) {        if (listView == null) {            return null;        }        final int firstListItemPosition = listView.getFirstVisiblePosition();        final int lastListItemPosition = firstListItemPosition + listView.getChildCount() - 1;        if (pos < firstListItemPosition || pos > lastListItemPosition ) {            // 如果在屏幕外,则利用getView重新获取一个itemView返回            return listView.getAdapter().getView(pos, null, listView);        } else {            // 如果在屏幕中则通过计算返回            final int childIndex = pos - firstListItemPosition;            return listView.getChildAt(childIndex);        }    }

得到指定View的宽度(必须保证已经layout已经传递)

    /**     * Returns the width as specified in the LayoutParams     * @throws IllegalStateException Thrown if the view's width is unknown before a layout pass     */    public static int getConstantPreLayoutWidth(View view) {        // We haven't been layed out yet, so get the size from the LayoutParams        final ViewGroup.LayoutParams p = view.getLayoutParams();        if (p.width < 0) {            throw new IllegalStateException("Expecting view's width to be a constant rather " +                    "than a result of the layout pass");        }        return p.width;    }

判断一个View是否是RTL的

    public static boolean isViewLayoutRtl(View view) {        return view.getLayoutDirection() == View.LAYOUT_DIRECTION_RTL;    }

得到一个bitmap长宽中较小的长度(不用解码效率较高)

    /**     * Returns Width or Height of the picture, depending on which size is smaller. Doesn't actually     * decode the picture, so it is pretty efficient to run.     */    public static int getSmallerExtentFromBytes(byte[] bytes) {        final BitmapFactory.Options options = new BitmapFactory.Options();        // don't actually decode the picture, just return its bounds        options.inJustDecodeBounds = true;        BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options);        // test what the best sample size is        return Math.min(options.outWidth, options.outHeight);    }

得到一个旋转指定角度的图片

    /**     * Retrieves a copy of the specified drawable resource, rotated by a specified angle.     *     * @param resources The current resources.     * @param resourceId The resource ID of the drawable to rotate.     * @param angle The angle of rotation.     * @return Rotated drawable.     */    public static Drawable getRotatedDrawable(            android.content.res.Resources resources, int resourceId, float angle) {        // Get the original drawable and make a copy which will be rotated.        Bitmap original = BitmapFactory.decodeResource(resources, resourceId);        Bitmap rotated = Bitmap.createBitmap(                original.getWidth(), original.getHeight(), Bitmap.Config.ARGB_8888);        // Perform the rotation.        Canvas tempCanvas = new Canvas(rotated);        tempCanvas.rotate(angle, original.getWidth()/2, original.getHeight()/2);        tempCanvas.drawBitmap(original, 0, 0, null);        return new BitmapDrawable(resources,rotated);    }

根据方形图片得到一个对应比例的圆形图片

    /**     * Given an input bitmap, scales it to the given width/height and makes it round.     *     * @param input {@link Bitmap} to scale and crop     * @param targetWidth desired output width     * @param targetHeight desired output height     * @return output bitmap scaled to the target width/height and cropped to an oval. The     *         cropping algorithm will try to fit as much of the input into the output as possible,     *         while preserving the target width/height ratio.     */    public static Bitmap getRoundedBitmap(Bitmap input, int targetWidth, int targetHeight) {        if (input == null) {            return null;        }        final Bitmap.Config inputConfig = input.getConfig();        final Bitmap result = Bitmap.createBitmap(targetWidth, targetHeight,                inputConfig != null ? inputConfig : Bitmap.Config.ARGB_8888);        final Canvas canvas = new Canvas(result);        final Paint paint = new Paint();        canvas.drawARGB(0, 0, 0, 0);        paint.setAntiAlias(true);        final RectF dst = new RectF(0, 0, targetWidth, targetHeight);        canvas.drawOval(dst, paint);        // Specifies that only pixels present in the destination (i.e. the drawn oval) should        // be overwritten with pixels from the input bitmap.        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));        final int inputWidth = input.getWidth();        final int inputHeight = input.getHeight();        // Choose the largest scale factor that will fit inside the dimensions of the        // input bitmap.        final float scaleBy = Math.min((float) inputWidth / targetWidth,            (float) inputHeight / targetHeight);        final int xCropAmountHalved = (int) (scaleBy * targetWidth / 2);        final int yCropAmountHalved = (int) (scaleBy * targetHeight / 2);        final Rect src = new Rect(                inputWidth / 2 - xCropAmountHalved,                inputHeight / 2 - yCropAmountHalved,                inputWidth / 2 + xCropAmountHalved,                inputHeight / 2 + yCropAmountHalved);        canvas.drawBitmap(input, src, dst, paint);        return result;    }
阅读全文
0 0
原创粉丝点击