banner



How To Draw On Black Canvas

Overview

Let'southward take a look at building a custom view that allows the user to pigment on the screen by pressing down their finger. This will illustrate how to build custom components, how to draw shapes and paths on a view and also how to handle user touch interactions.

Creating our Custom View

Create a elementary class for cartoon that extends View called SimpleDrawingView:

                      public            class            SimpleDrawingView            extends            View            {            public            SimpleDrawingView            (            Context            context            ,            AttributeSet            attrs            )            {            super            (            context            ,            attrs            );            }            }                  

Add together this to the XML layout for activity so our custom view is embedded inside:

                      <RelativeLayout            xmlns:android=            "http://schemas.android.com/apk/res/android"            xmlns:tools=            "http://schemas.android.com/tools"            android:layout_width=            "match_parent"            android:layout_height=            "match_parent"            tools:context=            ".MainActivity"            >            <com.codepath.example.simpledrawapp.SimpleDrawingView            android:id=            "@+id/simpleDrawingView1"            android:layout_width=            "wrap_content"            android:layout_height=            "wrap_content"            android:layout_alignParentBottom=            "true"            android:layout_alignParentLeft=            "truthful"            android:layout_alignParentRight=            "true"            android:layout_alignParentTop=            "true"            />            </RelativeLayout>                  

Simple Drawing with Canvas

Allow's endeavour drawing a couple of circles on screen. This requires usa to ascertain a Paint object which controls the styling and color of what is drawn. Allow's start past preparing the pigment:

                      public            grade            SimpleDrawingView            extends            View            {            // setup initial color            private            final            int            paintColor            =            Color            .            Blackness            ;            // defines paint and sheet            private            Paint            drawPaint            ;            public            SimpleDrawingView            (            Context            context            ,            AttributeSet            attrs            )            {            super            (            context            ,            attrs            );            setFocusable            (            true            );            setFocusableInTouchMode            (            true            );            setupPaint            ();            }            // Setup paint with color and stroke styles            individual            void            setupPaint            ()            {            drawPaint            =            new            Pigment            ();            drawPaint            .            setColor            (            paintColor            );            drawPaint            .            setAntiAlias            (            true            );            drawPaint            .            setStrokeWidth            (            five            );            drawPaint            .            setStyle            (            Paint            .            Way            .            STROKE            );            drawPaint            .            setStrokeJoin            (            Paint            .            Bring together            .            Circular            );            drawPaint            .            setStrokeCap            (            Paint            .            Cap            .            ROUND            );            }            }                  

Now that we have the paint setup to have a blackness colour and configured a particular stroke style, let's endeavor to draw a few circles with different colors. All cartoon that happens in a view should take place inside the onDraw method which is automatically called when a view is rendered:

                      public            course            SimpleDrawingView            extends            View            {            // ...variables and setting up paint...                        // Allow'due south depict three circles            @Override            protected            void            onDraw            (            Canvas            sail            )            {            canvas            .            drawCircle            (            50            ,            fifty            ,            20            ,            drawPaint            );            drawPaint            .            setColor            (            Color            .            Dark-green            );            canvas            .            drawCircle            (            l            ,            150            ,            twenty            ,            drawPaint            );            drawPaint            .            setColor            (            Color            .            Blue            );            canvas            .            drawCircle            (            50            ,            250            ,            20            ,            drawPaint            );            }            }                  

Find that onDraw passes us a canvas object which we use to depict leveraging the Paint nosotros defined earlier. The drawCircle method accepts the x, y and radius of the circle in addition to the pigment. This renders the following:

Circle

Treatment Touch Interactions

Suppose now we wanted to depict a circle every time the user touches downward on the drawing view. This would require us to continue track of an array of points for our circles and and so suspend a bespeak for each onTouch issue triggered:

                      public            grade            SimpleDrawingView            extends            View            {            // setup initial color            private            final            int            paintColor            =            Color            .            Blackness            ;            // defines pigment and canvas            individual            Paint            drawPaint            ;            // Shop circles to draw each time the user touches down            private            List            <            Point            >            circlePoints            ;            public            SimpleDrawingView            (            Context            context            ,            AttributeSet            attrs            )            {            super            (            context            ,            attrs            );            setupPaint            ();            // aforementioned as before            circlePoints            =            new            ArrayList            <            Point            >();            }            // Draw each circle onto the view            @Override            protected            void            onDraw            (            Canvass            sheet            )            {            for            (            Bespeak            p            :            circlePoints            )            {            canvas            .            drawCircle            (            p            .            10            ,            p            .            y            ,            5            ,            drawPaint            );            }            }            // Append new circle each fourth dimension user presses on screen            @Override            public            boolean            onTouchEvent            (            MotionEvent            event            )            {            float            touchX            =            issue            .            getX            ();            float            touchY            =            event            .            getY            ();            circlePoints            .            add            (            new            Point            (            Math            .            round            (            touchX            ),            Math            .            round            (            touchY            )));            // indicate view should be redrawn            postInvalidate            ();            return            truthful            ;            }            individual            void            setupPaint            ()            {            // same as earlier            drawPaint            .            setStyle            (            Paint            .            Style            .            FILL            );            // change to fill            // ...            }            }                  

with this, a black circumvolve is drawn each time we printing downwardly:

Circle 2

Cartoon with Paths

So far we have explored the onDraw method of a view and we were able to draw circles onto the view based on touch interactions with the view. Next, let'due south improve our drawing application past removing the listing of circles and instead drawing with paths. The Path grade is platonic for allowing the user to depict on screen. A path can contain many lines, contours and fifty-fifty other shapes. First, allow's add a Path variable to rail our drawing:

                      public            class            SimpleDrawingView            extends            View            {            // ...            private            Path            path            =            new            Path            ();            // ...            }                  

Next, let's suspend points to the path as the user touches the screen. When the user presses down, let's outset a path and then when they drag permit's connect the points together. To exercise this, we need modify the onTouchEvent to append these points to our Path object:

                      public            class            SimpleDrawingView            extends            View            {            private            Path            path            =            new            Path            ();            // Get x and y and append them to the path            public            boolean            onTouchEvent            (            MotionEvent            consequence            )            {            float            pointX            =            event            .            getX            ();            float            pointY            =            consequence            .            getY            ();            // Checks for the event that occurs            switch            (            event            .            getAction            ())            {            case            MotionEvent            .            ACTION_DOWN            :            // Starts a new line in the path            path            .            moveTo            (            pointX            ,            pointY            );            break            ;            case            MotionEvent            .            ACTION_MOVE            :            // Draws line between last betoken and this point            path            .            lineTo            (            pointX            ,            pointY            );            suspension            ;            default            :            return            false            ;            }            postInvalidate            ();            // Indicate view should be redrawn            return            truthful            ;            // Indicate nosotros've consumed the touch            }            // ...            }                  

and so let'due south alter the onDraw to remove the circles and instead to return the lines nosotros have plotted in our path:

                      public            class            SimpleDrawingView            extends            View            {            // ... onTouchEvent ...            // Draws the path created during the bear upon events            @Override            protected            void            onDraw            (            Canvas            canvas            )            {            canvas            .            drawPath            (            path            ,            drawPaint            );            }            private            void            setupPaint            ()            {            // same as before            drawPaint            .            setStyle            (            Paint            .            Style            .            STROKE            );            // change back to stroke            // ...            }            }                  

and with that, nosotros accept a very bones painting app that looks like:

Circle 3

Efficient Drawing with Bitmap Cache

When cartoon onto a canvas, you lot can often significantly better render times past caching the image into a bitmap every bit outlined in this stackoverflow postal service.

                      Bitmap            mField            =            naught            ;            public            void            init            ()            {            mField            =            new            Bitmap            (...            dimensions            ...);            Canvas            c            =            new            Sail            (            mField            );            c            .            drawRect            (...);            ...            }            public            void            onDraw            (            Canvas            c            )            {            c            .            drawBitmap            (            mField            );            }                  

This is a mutual pattern for improving drawing performance.

Reference for SimpleDrawingView

The full source code for our SimpleDrawingView:

                      package            com            .            codepath            .            case            .            simpledrawapp            ;            import            android.content.Context            ;            import            android.graphics.Canvass            ;            import            android.graphics.Color            ;            import            android.graphics.Paint            ;            import            android.graphics.Path            ;            import            android.util.AttributeSet            ;            import            android.view.MotionEvent            ;            import            android.view.View            ;            public            class            SimpleDrawingView            extends            View            {            // setup initial color            private            final            int            paintColor            =            Colour            .            Black            ;            // defines paint and canvas            private            Paint            drawPaint            ;            // stores next circle            private            Path            path            =            new            Path            ();            public            SimpleDrawingView            (            Context            context            ,            AttributeSet            attrs            )            {            super            (            context            ,            attrs            );            setFocusable            (            truthful            );            setFocusableInTouchMode            (            truthful            );            setupPaint            ();            }            private            void            setupPaint            ()            {            // Setup pigment with color and stroke styles            drawPaint            =            new            Paint            ();            drawPaint            .            setColor            (            paintColor            );            drawPaint            .            setAntiAlias            (            true            );            drawPaint            .            setStrokeWidth            (            five            );            drawPaint            .            setStyle            (            Pigment            .            Style            .            STROKE            );            drawPaint            .            setStrokeJoin            (            Paint            .            Bring together            .            ROUND            );            drawPaint            .            setStrokeCap            (            Pigment            .            Cap            .            Circular            );            }            @Override            protected            void            onDraw            (            Canvass            canvas            )            {            canvas            .            drawPath            (            path            ,            drawPaint            );            }            @Override            public            boolean            onTouchEvent            (            MotionEvent            issue            )            {            float            pointX            =            event            .            getX            ();            float            pointY            =            upshot            .            getY            ();            // Checks for the event that occurs            switch            (            upshot            .            getAction            ())            {            example            MotionEvent            .            ACTION_DOWN            :            path            .            moveTo            (            pointX            ,            pointY            );            return            true            ;            case            MotionEvent            .            ACTION_MOVE            :            path            .            lineTo            (            pointX            ,            pointY            );            break            ;            default            :            return            false            ;            }            // Force a view to draw again            postInvalidate            ();            return            true            ;            }            }                  

Drawing with Density Independent Pixels

When drawing or animating, you oftentimes want to draw using density independent pixels in club to be robust to unlike device sizes and densities. You may also want to determine the device elevation or width in order to draw intelligently. Re-create this DeviceDimensionsHelper.java utility grade to DeviceDimensionsHelper.java in your project and use anywhere that y'all have a context to determine screen dimensions or practice translations between dp and px:

                      // Become height or width of screen            int            screenHeight            =            DeviceDimensionsHelper            .            getDisplayHeight            (            this            );            int            screenWidth            =            DeviceDimensionsHelper            .            getDisplayWidth            (            this            );            // Catechumen dp to pixels            float            px            =            DeviceDimensionsHelper            .            convertDpToPixel            (            25            f            ,            this            );            // Catechumen pixels to dp            bladder            dp            =            DeviceDimensionsHelper            .            convertPixelsToDp            (            25            f            ,            this            );                  

You tin so use this to do smarter drawing for more than responsive custom views.

Source: https://guides.codepath.com/android/Basic-Painting-with-Views

Posted by: smithpere1940.blogspot.com

0 Response to "How To Draw On Black Canvas"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel