Home Web Front-end HTML Tutorial Use custom View to capture avatar page_html/css_WEB-ITnose

Use custom View to capture avatar page_html/css_WEB-ITnose

Jun 24, 2016 am 11:48 AM

In some applications, especially those with an account system, you can select pictures through the album and take pictures with the camera, then intercept the obtained avatar, and finally obtain the content in the selection box as the avatar. The general effect will be as follows Display:


So, how to create such an effect, and what are the key points?

There are actually many ways to do it,

1) You can directly inherit ImageView, and then directly draw a circular or square highlight circle in the OnDraw function of ImageView;

2) You can also directly inherit View, pass in the Bitmap yourself, draw the picture first in the onDraw function, then use Path to draw the circular or square selection area, and use Region.OP.DIFFERENCE to reversely obtain the mask layer. .

However, when using clipPath to draw this mask layer, the drawn circle will have jagged edges. I haven’t found a better way to remove the jagged edges yet. I wonder if any friends can provide it. Some suggestions.

The key codes are as follows:

    @Override    protected void onDraw(Canvas canvas) {                if(!mIsInit){            initCropRect(getWidth(), getHeight());            mOptBitmap = getProperBitmap(mBitmap, mCropRect.width());            ...               mIsInit = true;        }                canvas.save();        canvas.concat(mDrawMatrix);        canvas.drawBitmap(mOptBitmap, 0, 0, null);           canvas.restore();                   if(mToDrawHighlight){            canvas.save();            mPath.reset();                        if (mIsCircle) {                float radius = mCropRect.width() / 2 ;                mPath.addCircle(mCropRect.left + radius, mCropRect.top + radius, radius, Path.Direction.CW);            } else {                mPath.addRect(mCropRect, Path.Direction.CW);            }                                            canvas.clipPath(mPath, Region.Op.DIFFERENCE);            canvas.drawPaint(mDimPaint);            canvas.restore();                                }    }
Copy after login

Everyone only pays attention to the key codes.

First of all, during the first Ondraw, the size of the current View and bitmap can be obtained. At this time, we must first determine the CropRect, that is, the size and range of the selection box, whether it is a circle Shape or square, it is actually a square area, so you must first determine this area, which is implemented in the code initCropRect.

The operations that follow are actually some moving and scaling operations on the image. In order to center the image or enlarge a smaller image to the size of the selected area, you can ignore it for now.

Next, use canvas.drawBitmap to draw the corresponding bitmap.

The second step is to define a Path first, add a graphic to the path depending on whether to draw a circle or a square, and then use clipPath and Region.OP.DIFFERENCE to reversely obtain the mask area, and then Use mDimPaint to draw the mask on Canvas (mDimPaint is a brush with a semi-transparent color, so as not to cover up the bitmap painted underneath).


After drawing the mask and selection circle, more often, we need to move and zoom the image, similar to WeChat and Alipay, then we can use GestureDetector and ScaleGestureDetector to control movement and scaling, as follows:

mScaleGestureDetector = new ScaleGestureDetector(context, this);mGestureDetector = new GestureDetector(context, new MyGestureListener());
Copy after login

where MyGestureListener is a GestureDetector we customized, because we do not We don’t need too many Gestures, so we can use SimpleOnGestureListener to implement our processing, as follows:

    class MyGestureListener extends SimpleOnGestureListener {                @Override        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY){            mDrawMatrix.postTranslate(-distanceX, -distanceY);            checkBorderWhenTranslate();            return true;                                }           }
Copy after login

In fact, it is very simple. When the current View moves in a certain direction, We need to move the Canvas in the opposite direction, so that the drawn bitmap moves with our finger, so this is the reason why there is a negative distance here.

This is only for mobile and needs to be scaled. We need to implement an OnScaleGestureListener and let the current view implement this interface, as follows:

float scaleFactor = detector.getScaleFactor();                 float[] values = new float[9];        mDrawMatrix.getValues(values);        float curScale = values[Matrix.MSCALE_X];                if ((curScale < SCALE_MAX && scaleFactor > 1.0f) || (curScale > mInitScale && scaleFactor < 1.0f)) {                        if (scaleFactor * curScale < mInitScale) {                scaleFactor = mInitScale / curScale;            }            if (scaleFactor * curScale > SCALE_MAX) {                scaleFactor = SCALE_MAX / curScale;            }            mDrawMatrix.postScale(scaleFactor, scaleFactor, detector.getFocusX(), detector.getFocusY());            checkBorderAndCenterWhenScale();        }                return true;
Copy after login

The specific logic here depends on your own ideas. Finally, don’t forget, where to get these mobile events, of course, in the onTouch method, as follows:

    @Override    public boolean onTouch(View v, MotionEvent event) {        ...        mScaleGestureDetector.onTouchEvent(event);        mGestureDetector.onTouchEvent(event);              invalidate();        return true;    }    
Copy after login

Okay, this is the general idea about how to use a custom View to capture an avatar. You can improve it by yourself based on this idea.


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is HTML easy to learn for beginners? Is HTML easy to learn for beginners? Apr 07, 2025 am 12:11 AM

HTML is suitable for beginners because it is simple and easy to learn and can quickly see results. 1) The learning curve of HTML is smooth and easy to get started. 2) Just master the basic tags to start creating web pages. 3) High flexibility and can be used in combination with CSS and JavaScript. 4) Rich learning resources and modern tools support the learning process.

What is the purpose of the <progress> element? What is the purpose of the <progress> element? Mar 21, 2025 pm 12:34 PM

The article discusses the HTML &lt;progress&gt; element, its purpose, styling, and differences from the &lt;meter&gt; element. The main focus is on using &lt;progress&gt; for task completion and &lt;meter&gt; for stati

The Roles of HTML, CSS, and JavaScript: Core Responsibilities The Roles of HTML, CSS, and JavaScript: Core Responsibilities Apr 08, 2025 pm 07:05 PM

HTML defines the web structure, CSS is responsible for style and layout, and JavaScript gives dynamic interaction. The three perform their duties in web development and jointly build a colorful website.

What is the purpose of the <datalist> element? What is the purpose of the <datalist> element? Mar 21, 2025 pm 12:33 PM

The article discusses the HTML &lt;datalist&gt; element, which enhances forms by providing autocomplete suggestions, improving user experience and reducing errors.Character count: 159

What is the purpose of the <meter> element? What is the purpose of the <meter> element? Mar 21, 2025 pm 12:35 PM

The article discusses the HTML &lt;meter&gt; element, used for displaying scalar or fractional values within a range, and its common applications in web development. It differentiates &lt;meter&gt; from &lt;progress&gt; and ex

What is an example of a starting tag in HTML? What is an example of a starting tag in HTML? Apr 06, 2025 am 12:04 AM

AnexampleofastartingtaginHTMLis,whichbeginsaparagraph.StartingtagsareessentialinHTMLastheyinitiateelements,definetheirtypes,andarecrucialforstructuringwebpagesandconstructingtheDOM.

Understanding HTML, CSS, and JavaScript: A Beginner's Guide Understanding HTML, CSS, and JavaScript: A Beginner's Guide Apr 12, 2025 am 12:02 AM

WebdevelopmentreliesonHTML,CSS,andJavaScript:1)HTMLstructurescontent,2)CSSstylesit,and3)JavaScriptaddsinteractivity,formingthebasisofmodernwebexperiences.

Gitee Pages static website deployment failed: How to troubleshoot and resolve single file 404 errors? Gitee Pages static website deployment failed: How to troubleshoot and resolve single file 404 errors? Apr 04, 2025 pm 11:54 PM

GiteePages static website deployment failed: 404 error troubleshooting and resolution when using Gitee...

See all articles