Android profile picture, android profile picture
DIY round Avatar
Currently, most apps use circular portraits, and there are many open-source images on the Internet. But have you considered DIY circular portraits? Next we will implement one by ourselves. Let's take a look at the demo.
Step 1: Explanation of the principle (the picture is ugly and the principle is true)
1. Draw an external circle. Use a custom color to draw a circle, which is 5 DP longer than the image's radius.
2. After the custom circle is drawn, we need to convert the image into a circular Avatar and draw it on it. The image is overwritten from the middle to obtain the image.
3. intercept an image. Set the radius to r = min (width, height), center to cx = width/2, cy = height/2, in this way, the circular image can be captured from the center.
Step 2: code implementation
1. inherit the ImageView
2. Override the onDraw (Canvas canvas) method.
3. Set the image scaling type setScaleType (ScaleType. CENTER_CROP); intercept
The Code is as follows:
@ Overrideprotected void onDraw (Canvas canvas) {// super. onDraw (canvas); setScaleType (ScaleType. CENTER_CROP); Drawable drawable = getDrawable (); if (null = drawable) {return ;}// converts drawable to bitmap ==> Bitmap bitmap found on the internet = Bitmap. createBitmap (drawable. getIntrinsicWidth (), drawable. getIntrinsicHeight (), drawable. getOpacity ()! = PixelFormat. OPAQUE? Bitmap. config. ARGB_8888: Bitmap. config. RGB_565); Canvas srcCanvas = new Canvas (bitmap); drawable. setBounds (0, 0, drawable. getIntrinsicWidth (), drawable. getIntrinsicHeight (); drawable. draw (srcCanvas); float cx = getWidth ()/2; float cy = getHeight ()/2; float radius = Math. min (getWidth (), getHeight ()/2; Paint borderPaint = new Paint (); borderPaint. setAntiAlias (true); borderPaint. setColor (Color. GREEN); canvas. drawCircle (cx, cy, radius, borderPaint); // draw BitmapShader shader = new BitmapShader (bitmap, TileMode. CLAMP, TileMode. CLAMP); Paint paint = new Paint (); paint. setShader (shader); paint. setAntiAlias (true); canvas. drawCircle (cx, cy, radius-5, paint );}
The code is just a simple demo. Of course, you can customize it to a general CircleImageView. You need to DIY it as needed !!