1. 程式人生 > >自定義View(擦除蒙版得到背景,儲存圖片,更換背景)

自定義View(擦除蒙版得到背景,儲存圖片,更換背景)

效果圖:

這裡寫圖片描述

程式碼

MyBitmapTwo

package com.example.administrator.mywidgetmode.Bitmapview;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ComposePathEffect;
import
android.graphics.CornerPathEffect; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Path; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.Rect; import android.util.AttributeSet; import android.view.MotionEvent; import
android.view.View; import android.view.Window; import com.example.administrator.mywidgetmode.R; /** * Created by Administrator on 2015/9/17. */ public class MyBitmapTwo extends View{ private int width; private int height; private Bitmap mBitmap; private Paint mPaintCircel; private
Paint mPaintRect; private Canvas canvasBit; private Bitmap mBitmapBackground; private Matrix matrix; public MyBitmapTwo(Context context) { super(context); } public MyBitmapTwo(Context context, AttributeSet attrs) { super(context, attrs); path=new Path(); mBitmapBackground=BitmapFactory.decodeResource(getResources(),R.mipmap.d); matrix=new Matrix(); //黃色畫筆 mPaintCircel=new Paint(); mPaintCircel.setColor(Color.YELLOW); //綠色畫筆 mPaintRect=new Paint(); mPaintRect.setColor(Color.GREEN); //圖形交叉 PorterDuffXfermode mode=new PorterDuffXfermode(PorterDuff.Mode.XOR);//交叉的部分顯示背景 mPaintCircel.setXfermode(mode); //移動時用線 mPaintCircel.setStrokeJoin(Paint.Join.ROUND);//設定線段中間用圓形填充 mPaintCircel.setStrokeCap(Paint.Cap.ROUND);//設定線段開頭是圓形 mPaintCircel.setStrokeWidth(50); mPaintCircel.setStyle(Paint.Style.FILL_AND_STROKE);//非空心 mPaintCircel.setPathEffect(new CornerPathEffect(360)); mPaintCircel.setAntiAlias(true);//消鋸齒 } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); width = getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec); height = getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec); setMeasuredDimension(width, height);//設定畫布的大小,長和寬 mBitmap = Bitmap.createBitmap(width,height, Bitmap.Config.ARGB_8888); canvasBit=new Canvas(mBitmap); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.drawBitmap(mBitmapBackground,new Rect(0,0,mBitmapBackground.getWidth(),mBitmapBackground.getHeight()),new Rect(0,0,width,height),null);//用圖片做背景 //canvas.drawColor(Color.RED);//設定背景色 canvasBit.drawRect(0,0,width,height,mPaintRect);//跟view大小一樣的綠色矩形 canvasBit.drawPath(path,mPaintCircel);//按路徑畫圖形, // 這裡要注意,畫筆必須得是得到圖形交叉模式的畫筆 PorterDuffXfermode mode=new PorterDuffXfermode(PorterDuff.Mode.XOR);mPaintCircel.setXfermode(mode); canvas.drawBitmap(mBitmap, 0, 0, null); } float x; float y; float old_x; float old_y; private Path path; @Override//點選事件 public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()){ case MotionEvent.ACTION_DOWN: x=event.getX(); y=event.getY(); path.moveTo(x,y); invalidate(); old_x=x; old_y=y; return true; case MotionEvent.ACTION_MOVE: x=event.getX(); y=event.getY(); path.moveTo(old_x,old_y); path.lineTo(x,y); // path.quadTo((x+old_x)/2,(y+old_y)/2,x,y);//跟上面的lineTo效果一樣 invalidate(); old_x=x; old_y=y; return true; } return super.onTouchEvent(event); } }

MyBitmapTwoActivity

package com.example.administrator.mywidgetmode.Bitmapview;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

import com.example.administrator.mywidgetmode.R;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by Administrator on 2015/9/17.
 */
public class MyBitmapTwoActivity extends AppCompatActivity {
    private Button mBt;
    private MyBitmapTwo myBitmapTwo;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bitmap_two);
        myBitmapTwo= (MyBitmapTwo) findViewById(R.id.myBitmapTwo);
        mBt= (Button) findViewById(R.id.button_jpg);
        mBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myBitmapTwo.setDrawingCacheEnabled(true);
                Bitmap bitmap=myBitmapTwo.getDrawingCache(true);
                File file=new File(Environment.getExternalStorageDirectory(),System.currentTimeMillis()+".jpg");
                if(!file.exists()){
                    try {
                        file.createNewFile();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    try {
                        bitmap.compress(Bitmap.CompressFormat.JPEG,100,new FileOutputStream(file));
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }
}

layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <Button
        android:id="@+id/button_jpg"
        android:text="儲存圖片"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <com.example.administrator.mywidgetmode.Bitmapview.MyBitmapTwo
        android:id="@+id/myBitmapTwo"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

更換背景

自己寫一個values

myview_attr

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="myview">
        <attr name="myview_backgroud" format="reference"></attr>
        <attr name="myview_paintwidth" format="dimension|reference"></attr>
    </declare-styleable>
</resources>

layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:myview="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <Button
        android:id="@+id/button_jpg"
        android:text="儲存圖片"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <com.example.administrator.mywidgetmode.Bitmapview.MyBitmapTwo
        android:id="@+id/myBitmapTwo"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        myview:myview_backgroud="@mipmap/b"
        myview:myview_paintwidth="30dp"/>
</LinearLayout>

MyBitmapTwo
在重寫MyBitmapTwo方法里加入下面的程式碼,更換背景,和自定義畫筆的大小

 final TypedArray typedArray=context.obtainStyledAttributes(attrs,R.styleable.myview);
        BitmapDrawable dra = (BitmapDrawable) typedArray.getDrawable(R.styleable.myview_myview_backgroud);
        if (dra!=null){
            Log.d("drawable",""+dra.getIntrinsicWidth());
            mBitmapBackground=dra.getBitmap();
        }else {
            mBitmapBackground=BitmapFactory.decodeResource(getResources(),R.mipmap.d);
        }
        int paintWidth=typedArray.getDimensionPixelOffset(R.styleable.myview_myview_paintwidth,30);