在Android中创建固定比率大小视图

时间:2015-04-09 10:32:22

标签: android android-drawable

我正在尝试开发一款可以读卡的应用。为此,我需要绘制卡片大小比例透明盒子,以便用户可以将他/她的卡片放入其中(例如:http://i.stack.imgur.com/WTgpU.png)。此框必须与设备无关。此外,对于所有设备,图像必须是固定大小,如450 * 300。 直到现在我已经创建了一个drawable并在视图中调用它。

我的Drawable代码是:

<?xml version="1.0" encoding="UTF-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/listview_background_shape">
    <stroke android:width="2dp" android:color="#ff207d94" />
    <padding android:left="2dp"
        android:top="2dp"
        android:right="2dp"
        android:bottom="2dp" />
    <corners android:radius="5dp" />
    <solid android:color="#88000000" />
</shape>

我的主要布局:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <SurfaceView
            android:id="@+id/cameraview"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent" />

        <View
            android:id="@+id/myRectangleView"
            android:layout_width="337dp" 
            android:layout_height="213dp"
            android:background="@drawable/rectangle"
            android:layout_gravity="center"/>

    </FrameLayout>

     <Button
         android:id="@+id/capture"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:layout_alignParentBottom="true"
         android:layout_alignParentLeft="true"
         android:text="@string/Capture" />

     <ImageView
         android:id="@+id/image"
         android:layout_width="fill_parent"
         android:layout_height="fill_parent"/>

2 个答案:

答案 0 :(得分:0)

试试这个,

  1. 以像素为单位获取设备宽度和高度。
  2. 定义视图的比例(根据图像,它更像是设备宽度的0.9和设备高度的0.5)

  3. 现在您可以计算所需的框宽度和高度

    width = 0.9 * device_width_pixels  ,   height = 0.5 * device_height_pixels
    
  4. 使用计算值设置视图尺寸。

答案 1 :(得分:0)

您可以创建自己的自定义View并覆盖onMeasure方法。 例如,对于正方形(1:1)FrameLayout

public class SquareFrameLayout extends FrameLayout {

    public SquareFrameLayout(final Context context) {
        super(context);
    }

    public SquareFrameLayout(final Context context, final AttributeSet attrs) {
        super(context, attrs);
    }

    public SquareFrameLayout(final Context context, final AttributeSet attrs, final int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onMeasure(int width, int height) {
        super.onMeasure(width, height);
        int measuredWidth = getMeasuredWidth();
        setMeasuredDimension(measuredWidth, measuredWidth);
    }

}