I used to find a method to crop a circular image in the EOE forum, but the results were not very satisfactory. In the past few days, due to the company's business requirements, we need to crop the Avatar in a circular shape.
This method is determined based on the height and width of the input image. If it is width <= height
The crop area is the length of the width from top to width. If width>
The width is cropped. The cropped area is the center area of the image width and the width is the image width. However, different business requirements have different requirements for the cropped image, can be adjusted based on business needs
The area of the cropped area.
Okay, let's just move on.Code
/** * Convert the image to a circle * @ Param Transfer bitmap objects * @ Return */ Public Bitmap toroundbitmap (Bitmap bitmap ){ Int Width = Bitmap. getwidth (); Int Height = Bitmap. getheight (); Float Roundpx; Float Left, top, right, bottom, dst_left, dst_top, dst_right, dst_bottom; If (Width <= Height) {roundpx = Width/2; Top = 0 ; Bottom = Width; left = 0 ; Right = Width; Height = Width; dst_left = 0 ; Dst_top = 0 ; Dst_right = Width; dst_bottom = Width ;} Else {Roundpx = Height/2 ; Float Clip = (width-height)/2 ; Left = Clip; Right = Width- Clip; top = 0 ; Bottom = Height; Width = Height; dst_left = 0; Dst_top = 0 ; Dst_right = Height; dst_bottom = Height;} bitmap output = Bitmap. createbitmap (width, height, config. argb_8888); canvas = New Canvas (output ); Final Int Color = 0xff0000242 ; Final Paint paint = New Paint (); Final Rect src = New Rect (( Int ) Left ,( Int ) Top ,( Int ) Right ,( Int ) Bottom ); Final Rect DST = New Rect (( Int ) Dst_left ,(Int ) Dst_top ,( Int ) Dst_right ,( Int ) Dst_bottom ); Final Rectf = New Rectf (DST); paint. setantialias ( True ); Canvas. drawargb ( 0, 0, 0, 0 ); Paint. setcolor (color); canvas. drawroundrect (rectf, roundpx, roundpx, paint); paint. setxfermode ( New Porterduxfermode (mode. src_in); canvas. drawbitmap (bitmap, SRC, DST, paint ); Return Output ;}