Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add rounded corners to custom view

I'm quite new to Android and i'm trying to draw on a custom view (with canvas). I've got some lines & rects there. The point is, that i now want to give the whole view rounded corners, but that doesn't work well, as i'm drawing on the view and my drawings are above the rounded corners, which were added through the ressources. Is there a possibility to add rounded corners, that cover the whole view?

Best regards and thank's for any help!

like image 419
Lukas Avatar asked Jan 14 '23 06:01

Lukas


1 Answers

I am not sure of your requirements. But you can use the below and modify the same

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/rl"
android:background="@drawable/bkg" //set background
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
</RelativeLayout>

bkg.xml

 <?xml version="1.0" encoding="UTF-8"?> 
 <shape xmlns:android="http://schemas.android.com/apk/res/android"
 android:shape="rectangle"> 
 <solid android:color="#10EB0A"/>    //set color
 <stroke android:width="3dp"         // set border  
 android:color="#0FECFF" />          //set border color 
 <padding android:left="5dp"         //set padding
 android:top="5dp" 
 android:right="5dp"
 android:bottom="5dp"/> 
 <corners android:bottomRightRadius="20dp" //set radius
 android:bottomLeftRadius="20dp" 
 android:topLeftRadius="20dp"
 android:topRightRadius="20dp"/> 
 </shape> 

MainActivity.java

    public class MainActivity extends Activity {

RelativeLayout rl;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    rl = (RelativeLayout) findViewById(R.id.rl);
    CustomView cv = new CustomView(this);
    rl.addView(cv);  //add custom view to the relative layout
} 

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}
class CustomView extends View
{
    Bitmap bmp;
    PaintDrawable mDrawable;

    public CustomView(Context context) {
        super(context); 
        bmp = BitmapFactory.decodeResource(context.getResources(),R.drawable.ic_launcher);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        // TODO Auto-generated method stub
        super.onDraw(canvas);

        canvas.drawBitmap(bmp, 200, 200, null);
    }   
       }
  }

Snap shot

enter image description here

like image 115
Raghunandan Avatar answered Jan 29 '23 02:01

Raghunandan