Wednesday, November 18, 2015

android - How to rotate a Canvas

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context=".MainActivity"
    android:background="#b4b9cc"
    >
    <ImageView
        android:id="@+id/iv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Draw"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentBottom="true"
        />
</RelativeLayout>
MainActivity.java

package com.cfsuman.me.androidcode;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.Paint;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.graphics.Canvas;
import android.graphics.Bitmap;


public class MainActivity extends AppCompatActivity {
    private Context mContext;
    private Resources mResources;
    private RelativeLayout mRelativeLayout;
    private Button mButton;
    private ImageView mImageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Get the application context
        mContext = getApplicationContext();

        // Get the Resources
        mResources = getResources();

        // Get the widgets reference from XML layout
        mRelativeLayout = (RelativeLayout) findViewById(R.id.rl);
        mButton = (Button) findViewById(R.id.btn);
        mImageView = (ImageView) findViewById(R.id.iv);

        // Set a click listener for Button widget
        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Initialize a new Bitmap
                Bitmap bitmap = Bitmap.createBitmap(
                        600, // Width
                        300, // Height
                        Bitmap.Config.ARGB_8888 // Config
                );

                // Initialize a new Canvas instance
                Canvas canvas = new Canvas(bitmap);

                // Draw a solid color on the canvas as background
                canvas.drawColor(Color.YELLOW);

                // Initialize a new Paint instance to draw on canvas
                Paint paint = new Paint();
                paint.setStyle(Paint.Style.FILL);
                paint.setColor(Color.RED);
                paint.setAntiAlias(true);

                // Set an offset value in pixels to draw rectangle on canvas
                int offset = 100;

                /*
                    public int save (int saveFlags)
                        Based on saveFlags, can save the current matrix and clip onto a private stack.

                        Note: if possible, use the parameter-less save(). It is simpler and faster
                        than individually disabling the saving of matrix or clip with this method.

                        Subsequent calls to translate,scale,rotate,skew,concat or clipRect, clipPath
                        will all operate as usual, but when the balancing call to restore() is made,
                        those calls will be forgotten, and the settings that existed before the
                        save() will be reinstated.

                    Parameters
                        saveFlags : flag bits that specify which parts of the Canvas state to save/restore
                    Returns
                        The value to pass to restoreToCount() to balance this save()
                */

                /*
                    MATRIX_SAVE_FLAG
                        Restore the current matrix when restore() is called.
                */

                // Save the canvas state
                canvas.save(Canvas.MATRIX_SAVE_FLAG);

                /*
                    public final void rotate (float degrees, float px, float py)
                        Preconcat the current matrix with the specified rotation.

                    Parameters
                        degrees : The amount to rotate, in degrees
                        px : The x-coord for the pivot point (unchanged by the rotation)
                        py : The y-coord for the pivot point (unchanged by the rotation)
                */

                // Rotate the canvas
                canvas.rotate(
                        25, // degrees
                        canvas.getWidth() / 2, // px, center x
                        canvas.getHeight() / 2 // py, center y
                );

                // Draw the rounded corners rectangle object on the canvas
                // The rectangle will be drawn as a 25 degrees rotated rectangle
                canvas.drawRect(
                        offset, // left
                        offset, // top
                        canvas.getWidth() - offset, // right
                        canvas.getHeight() - offset, // bottom
                        paint // Paint
                );

                /*
                    public void restore ()
                        This call balances a previous call to save(), and is used to remove all
                        modifications to the matrix/clip state since the last save call. It is an
                        error to call restore() more times than save() was called.
                */

                // Finally, restore the canvas state
                canvas.restore();

                // Display the newly created bitmap on app interface
                mImageView.setImageBitmap(bitmap);
            }
        });
    }
}
More android examples