开发者

Android: drawing on views canvas doesn't work

开发者 https://www.devze.com 2023-04-01 05:33 出处:网络
I\'m tryin to draw a shape on a canvas under all buttons. Here\'s the code: Paint paint = new Paint(); paint.setColor(R.color.Kolor);

I'm tryin to draw a shape on a canvas under all buttons. Here's the code:

Paint paint = new Paint();
paint.setColor(R.color.Kolor);

View view; 
LayoutInflater inflater = (LayoutInflater)
getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
view = inflater.inflate(R.layout.menu_glowne, null);

Canvas can = new Canvas(Bitmap.createBitmap开发者_运维百科(300, 300, Bitmap.Config.ARGB_8888));
can.drawRect(0, 0, 200, 200, paint);

setContentView(view);

view.draw(can);

Don't know why I'm still getting the layout without anything drawn underneath. Any ideas on what I'm doing wrong?

Thanx in advance!


In your example you are drawing the view on your canvas rather than on canvas of the view. You should use a simple approach, don't inflate your layout but load it normally, then find the root container and set its background. Something like this:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Paint paint = new Paint();
    paint.setColor(Color.MAGENTA);
    Bitmap bgr = Bitmap.createBitmap(480, 800, Bitmap.Config.ARGB_8888); 
    Canvas can = new Canvas(bgr);  
    can.drawRect(50, 50, 200, 200, paint);  
    LinearLayout ll = (LinearLayout) findViewById(R.id.ll); 
    ll.setBackgroundDrawable(new BitmapDrawable(bgr));    

}

main layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" 
    android:id="@+id/ll">
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
    />
</LinearLayout>


You don't draw this way in android. Everything happens through a method override (onDraw). Follow this tutorial to get started : http://www.helloandroid.com/tutorials/how-use-canvas-your-android-apps-part-1

Regards, Stéphane

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号