Crop square image to circle - Programmatically

前端 未结 7 1425
余生分开走
余生分开走 2020-12-01 01:14

i was searching for past one day and i was not successful .

i get the image from API , and i download it to a bitmap file using the following code .

         


        
7条回答
  •  一向
    一向 (楼主)
    2020-12-01 01:45

    After hunting lot of answers I came up with this small hack which exploits FrameLayout(overlays child views as a stack) and stroke attribute of oval-shape. This can be done simply in XML without much hassle and third party libraries.

    1. Create new Layout resource file "circle_image.xml" under res/layout directory.
    2. Add a new FrameLayout as the root view in the circle_image.xml.
    3. Create an ImageView (base/background) to hold your Image or Icon which you want to crop as the first child in the FrameLayout.
    4. Create an ImageView (mask/foreground) to hold the shape(oval made into circle with size attribute having same height and width) that masks the background image as the second/last child inside the FrameLayout.

    Note:

    our idea here is to exclude the area around the circle and display the contents of the image that is visible inside the circle)

    1. Create new Drawable resource file "circle_mask.xml" under res/drawable directory.
    2. Add new shape with android:shape="oval" in the circle_mask.xml.
    3. Add size tag for the shape to specify height and width which must be equal(to make it a circle) and should match that of its parent FrameLayout.
    4. Add solid tag for the shape to specify the transparency inside the circle. 10.Add stroke tag for the shape so that there will be a ring of particular width(android:width) with the color specified by the android:color attribute.

    Note:

    a. The color(stroke color) specified in the stoke tag is the MaskColor/BackgroundColor around our cropped image. since I wanted this color to be same as that of my base view which was a cardView. I used the same color "white".

    b. The width (stroke width) is set to a huge value such that it is too thick with enough space for our cropped image in the centre.

    c. The ImageView(top mask layer) created in Step-4 is also exploited by specifying a huge dimension that is much larger than its parent FrameLayout making it expand outside the FrameLayout dimensions. This fills up the area which we are interested in masking with the color of large stroke width ring.

    circle_image.xml

    
    
        
    
    
        
        
    
    

    circle_mask.xml

    
    
        
        
        
    
    

提交回复
热议问题