Android 笔记

Android 中 dp 与 px 互转

很简单,操作系统本身已提供了需要的数据

// 获取 dp 到 px 的倍数
float dp_to_px = getContext().getResources().getDisplayMetrics().density;
// 将 16dp 转换 px
int dp = 16;
int px = (int)(dp * dp_to_px);
// 将 320px 转换 dp
int px = 320;
int dp = (int)(px / dp_to_px);

在 Canvas 上绘制 View的方法

View view = LayoutInflater.from(Context).inflate(R.layout.~~, parent, false);
fixLayoutSize(view, parent);
// 保存画布
canvas.save();
// 移动画布的坐标原点
canvas.translate(dx, dy);
// 绘制这个 view
view.draw(canvas);
// 恢复画布
canvas.restore();
// 确保 view 有正确的尺寸
void fixLayoutSize(View view, ViewGroup parent) {
    if (view.getLayoutParams() == null) {
        view.setLayoutParams(new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT));
    }

    int widthSpec = View.MeasureSpec.makeMeasureSpec(
                        parent.getWidth(), View.MeasureSpec.EXACTLY);

    int heightSpec = View.MeasureSpec.makeMeasureSpec(
                        parent.getHeight(), View.MeasureSpec.EXACTLY);

    int childWidth = ViewGroup.getChildMeasureSpec(widthSpec,
                        parent.getPaddingLeft() + parent.getPaddingRight(),
                        view.getLayoutParams().width);

    int childHeight = ViewGroup.getChildMeasureSpec(heightSpec,
                        parent.getPaddingTop() + parent.getPaddingBottom(),
                        view.getLayoutParams().height);

    view.measure(childWidth, childHeight);
    view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
}

你可能感兴趣的:(Android)