Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: How to make circle-shaped Camera Preview?

How can I create circle/oval-shaped or round-cornered Camera Preview like this (the circle in the middle should be camera preview)?

enter image description here

The London image represents rest of the ui with buttons and views, so it has to be visible whole and that's why I cannot use solutions like add android:background as a shape rectangle with radius like this:

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#FFFFFF"/>
    <stroke android:width="3dip" android:color="#B1BCBE" />
    <corners android:radius="50dip"/>
    <padding android:left="0dip" android:top="0dip" android:right="0dip" android:bottom="0dip" />
</shape>

and when I try to set android:background as oval xml to the SurfaceView, it doesn't work either:

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">

    <size
        android:width="120dp"
        android:height="120dp"/>

    <stroke
        android:color="#FF000000"
        android:width="2dp" />
</shape>

If it is possible to somehow extend SurfaceView and use it, what should I rewrite please?

like image 278
Jakub Turcovsky Avatar asked Mar 18 '15 14:03

Jakub Turcovsky


1 Answers

You can use a CardView to a house your textureView or surfaceArea like this.

<androidx.cardview.widget.CardView
        android:id="@+id/cameraWrapper"
        android:layout_width="300dp"
        android:layout_height="300dp"
        app:cardCornerRadius="360dp"
        android:foreground="@drawable/background_camera_overlay_circle_inactive"
        app:cardElevation="0dp"
        android:padding="-20dp">

        <com.mobile.myapp.CustomViews.CameraSourcePreview //you can use SurfaceView, TextView, ImageView
            android:id="@+id/preview"
            android:layout_width="400dp"
            android:layout_height="400dp"/></androidx.cardview.widget.CardView>

The key things to note.

  • cornerRadius is set to 360 to get the CardView to have a round shape
  • cardElevation is set to zero to remove elevation, thereby making the CardView flat
  • padding is set to a negative value so that the child view is tucked in nicely
  • layout_width and layout_height values of the child view are bigger than that of the cardView.
  • The CardView has a foreground property that has been set to a drawable file background_camera_overlay_circle, which simply draws the circle border

The content of background_camera_overlay_circle

<?xml version="1.0" encoding="utf-8"?>
    <shape android:shape="oval" xmlns:android="http://schemas.android.com/apk/res/android">
     <stroke android:width="5dp" android:color="@color/colorRed_FB7B7B"/>
  </shape>

Give it a try.

like image 95
Kenneth Ngedo Avatar answered Oct 03 '22 01:10

Kenneth Ngedo