【问题标题】:set the canvas size - Android设置画布大小 - Android
【发布时间】:2011-12-27 12:06:51
【问题描述】:

我想为画布保持相同大小的位图,因为当我将自定义视图添加到 LinearLayout 时会显示不同大小的画布,我想像位图对象一样设置画布的大小。

部分代码:

public class TESTActivity extends Activity {    

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        LinearLayout l = new LinearLayout(this);
        l.setOrientation(1);
        Button b1 = new Button(this);
        Button b2 = new Button(this);
        View mV = new MyView(this);        
        l.addView(b1);
        l.addView(b2);
        l.addView(mV);       
        setContentView(l);

    }


    public class MyView extends View {


        public MyView(Context c) {
            super(c);
            mBitmap = Bitmap.createBitmap(480, 300, Bitmap.Config.ARGB_8888);
            mCanvas = new Canvas(mBitmap);
            ...
        }
        ...
    }
}

【问题讨论】:

标签: android view canvas android-linearlayout


【解决方案1】:

Canvas 类拥有“draw”调用。 Canvas(Bitmap bitmap) 用指定的位图构造一个画布来绘制。画布将采用绘图对象的大小。所以通过设置位图的大小,你可以设置画布的大小。

【讨论】:

  • 那为什么Canvas的颜色和Bitmap的颜色不一样,让视图更大呢?我重写 onSizeChanged 来测试大小并给我宽度 480 和高度 536 的值,我的位图是 480x300。怎么了?谢谢
【解决方案2】:

如果您想使用自定义高度和宽度在画布上绘图,您必须在活动类中调用 setContentView(android.view.View yourView , android.view.Viewgroup.LayoutParam yourLayout)。因为默认情况下 setContentView(View view) 方法使用全宽和全高。所以你必须使用它的重载方法和你想要的两个参数。有关更多信息,请参阅文档。不要仅使用 LayoutParams() 构造函数来创建其对象。通过编写其完整路径来使用它,例如 android.view.ViewGroup.LayoutParams。因为Android SDK中还有其他一些同名的类。如果你只使用LayoutParams Eclipse可能找不到正确的类所以使用完整路径。

MyView customView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    customView = new MyView(getApplicationContext());
    android.view.ViewGroup.LayoutParams lp = new android.view.ViewGroup.LayoutParams(100,200);//100 is width and 200 is height
    setContentView(customView, lp);
    customView.setOnClickListener(this);

}`  

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-04
    • 1970-01-01
    • 2016-03-19
    • 2016-10-27
    • 1970-01-01
    • 1970-01-01
    • 2013-04-10
    相关资源
    最近更新 更多