Android开发中那些有用的方法

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

获取屏幕宽度

    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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值