Android 繪圖類實(shí)戰(zhàn)示例

2023-03-31 14:18 更新

本節(jié)引言:

前兩節(jié)我們學(xué)了Bitmap和一些基本的繪圖API的屬性以及常用的方法,但心里總覺(jué)得有點(diǎn) 不踏實(shí),總得寫(xiě)點(diǎn)什么加深下映像是吧,嗯,本節(jié)我們就來(lái)寫(xiě)兩個(gè)簡(jiǎn)單的例子:

  • 1.簡(jiǎn)單畫(huà)圖板的實(shí)現(xiàn)
  • 2.幫美女擦衣服的簡(jiǎn)單實(shí)現(xiàn)

嘿嘿,第二個(gè)例子是小豬剛學(xué)安卓寫(xiě)的一個(gè)小Demo~嘿嘿~ 開(kāi)始本節(jié)內(nèi)容~


1.實(shí)戰(zhàn)示例1:簡(jiǎn)單畫(huà)圖板的實(shí)現(xiàn):

這個(gè)相信大家都不陌生,很多手機(jī)都會(huì)自帶一個(gè)給用戶涂鴉的畫(huà)圖板,這里我們就來(lái)寫(xiě)個(gè)簡(jiǎn)單的 例子,首先我們分析下,實(shí)現(xiàn)這個(gè)東東的一些邏輯:

Q1:這個(gè)畫(huà)板放在哪里?

答:View里,我們自定義一個(gè)View,在onDraw()里完成繪制,另外View還有個(gè)onTouchEvent的方法, 我們可以在獲取用戶的手勢(shì)操作!

Q2.需要準(zhǔn)備些什么?

答:一只畫(huà)筆(Paint),一塊畫(huà)布(Canvas),一個(gè)路徑(Path)記錄用戶繪制路線; 另外劃線的時(shí)候,每次都是從上次拖動(dòng)時(shí)間的發(fā)生點(diǎn)到本次拖動(dòng)時(shí)間的發(fā)生點(diǎn)!那么之前繪制的 就會(huì)丟失,為了保存之前繪制的內(nèi)容,我們可以引入所謂的"雙緩沖"技術(shù): 其實(shí)就是每次不是直接繪制到Canvas上,而是先繪制到Bitmap上,等Bitmap上的繪制完了, 再一次性地繪制到View上而已!

Q3.具體的實(shí)現(xiàn)流程?

答:初始化畫(huà)筆,設(shè)置顏色等等一些參數(shù);在View的onMeasure()方法中創(chuàng)建一個(gè)View大小的Bitmap, 同時(shí)創(chuàng)建一個(gè)Canvas;onTouchEvent中獲得X,Y坐標(biāo),做繪制連線,最后invalidate()重繪,即調(diào)用 onDraw方法將bitmap的東東畫(huà)到Canvas上!

好了,邏輯知道了,下面就上代碼了:

MyView.java

/**
 * Created by Jay on 2015/10/15 0015.
 */
public class MyView extends View{

    private Paint mPaint;  //繪制線條的Path
    private Path mPath;      //記錄用戶繪制的Path
    private Canvas mCanvas;  //內(nèi)存中創(chuàng)建的Canvas
    private Bitmap mBitmap;  //緩存繪制的內(nèi)容

    private int mLastX;
    private int mLastY;

    public MyView(Context context) {
        super(context);
        init();
    }

    public MyView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public MyView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init(){
        mPath = new Path();
        mPaint = new Paint();   //初始化畫(huà)筆
        mPaint.setColor(Color.GREEN);
        mPaint.setAntiAlias(true);
        mPaint.setDither(true);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeJoin(Paint.Join.ROUND); //結(jié)合處為圓角
        mPaint.setStrokeCap(Paint.Cap.ROUND); // 設(shè)置轉(zhuǎn)彎處為圓角
        mPaint.setStrokeWidth(20);   // 設(shè)置畫(huà)筆寬度
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int width = getMeasuredWidth();
        int height = getMeasuredHeight();
        // 初始化bitmap,Canvas
        mBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        mCanvas = new Canvas(mBitmap);
    }

    //重寫(xiě)該方法,在這里繪圖
    @Override
    protected void onDraw(Canvas canvas) {
        drawPath();
        canvas.drawBitmap(mBitmap, 0, 0, null);
    }

    //繪制線條
    private void drawPath(){
        mCanvas.drawPath(mPath, mPaint);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {

        int action = event.getAction();
        int x = (int) event.getX();
        int y = (int) event.getY();

        switch (action)
        {
            case MotionEvent.ACTION_DOWN:
                mLastX = x;
                mLastY = y;
                mPath.moveTo(mLastX, mLastY);
                break;
            case MotionEvent.ACTION_MOVE:
                int dx = Math.abs(x - mLastX);
                int dy = Math.abs(y - mLastY);
                if (dx > 3 || dy > 3)
                    mPath.lineTo(x, y);
                mLastX = x;
                mLastY = y;
                break;
        }

        invalidate();
        return true;
    }
}

運(yùn)行效果圖

你可以根據(jù)自己的需求進(jìn)行擴(kuò)展,比如加上修改畫(huà)筆大小,修改畫(huà)筆顏色,保存自己畫(huà)的圖等! 發(fā)散思維,自己動(dòng)手~


2.實(shí)戰(zhàn)示例2:擦掉美女衣服的實(shí)現(xiàn)

核心思路是: 利用幀布局,前后兩個(gè)ImageView,前面的顯示未擦掉衣服的情況,后面的顯示擦掉衣服后的情況!

為兩個(gè)ImageView設(shè)置美女圖片后,接著為前面的ImageView設(shè)置OnTouchListener!在這里對(duì)手指 觸碰點(diǎn)附近的20*20個(gè)像素點(diǎn),設(shè)置為透明!

運(yùn)行效果圖

代碼實(shí)現(xiàn)

Step 1:第一個(gè)選妹子的Activity相關(guān)的編寫(xiě),首先是界面,一個(gè)ImageView,Button和Gallery!

activity_main.xml

<?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">

    <ImageView
        android:id="@+id/img_choose"
        android:layout_width="320dp"
        android:layout_height="320dp" />

    <Button
        android:id="@+id/btn_choose"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="脫光她!" />

    <Gallery
        android:id="@+id/gay_choose"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="25dp"
        android:spacing="1pt"
        android:unselectedAlpha="0.6" />

</LinearLayout>

接著是我們Gallery的Adapter類,這里我們重寫(xiě)下BaseAdapter,而里面就顯示一個(gè)圖片比較簡(jiǎn)單, 就不另外寫(xiě)一個(gè)布局了!

MeiziAdapter.java:

/**
 * Created by Jay on 2015/10/16 0016.
 */
public class MeiziAdapter extends BaseAdapter{

    private Context mContext;
    private int[] mData;

    public MeiziAdapter() {
    }

    public MeiziAdapter(Context mContext,int[] mData) {
        this.mContext = mContext;
        this.mData = mData;
    }

    @Override
    public int getCount() {
        return mData.length;
    }

    @Override
    public Object getItem(int position) {
        return mData[position];
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView imgMezi = new ImageView(mContext);
        imgMezi.setImageResource(mData[position]);         //創(chuàng)建一個(gè)ImageView
        imgMezi.setScaleType(ImageView.ScaleType.FIT_XY);      //設(shè)置imgView的縮放類型
        imgMezi.setLayoutParams(new Gallery.LayoutParams(250, 250));    //為imgView設(shè)置布局參數(shù)
        TypedArray typedArray = mContext.obtainStyledAttributes(R.styleable.Gallery);
        imgMezi.setBackgroundResource(typedArray.getResourceId(R.styleable.Gallery_android_galleryItemBackground, 0));
        return imgMezi;
    }
}

最后到我們的Activity,也很簡(jiǎn)單,無(wú)非是為gallery設(shè)置onSelected事件,點(diǎn)擊按鈕后把,當(dāng)前選中的 Position傳遞給下一個(gè)頁(yè)面!

MainActivity.java

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener,
        View.OnClickListener {

    private Context mContext;
    private ImageView img_choose;
    private Button btn_choose;
    private Gallery gay_choose;
    private int index = 0;
    private MeiziAdapter mAdapter = null;
    private int[] imageIds = new int[]
            {
                    R.mipmap.pre1, R.mipmap.pre2, R.mipmap.pre3, R.mipmap.pre4,
                    R.mipmap.pre5, R.mipmap.pre6, R.mipmap.pre7, R.mipmap.pre8,
                    R.mipmap.pre9, R.mipmap.pre10, R.mipmap.pre11, R.mipmap.pre12,
                    R.mipmap.pre13, R.mipmap.pre14, R.mipmap.pre15, R.mipmap.pre16,
                    R.mipmap.pre17, R.mipmap.pre18, R.mipmap.pre19, R.mipmap.pre20,
                    R.mipmap.pre21
            };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = MainActivity.this;
        bindViews();
    }

    private void bindViews() {
        img_choose = (ImageView) findViewById(R.id.img_choose);
        btn_choose = (Button) findViewById(R.id.btn_choose);
        gay_choose = (Gallery) findViewById(R.id.gay_choose);

        mAdapter = new MeiziAdapter(mContext, imageIds);
        gay_choose.setAdapter(mAdapter);
        gay_choose.setOnItemSelectedListener(this);
        btn_choose.setOnClickListener(this);

    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        img_choose.setImageResource(imageIds[position]);
        index = position;
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {
    }

    @Override
    public void onClick(View v) {
        Intent it = new Intent(mContext,CaClothes.class);
        Bundle bundle = new Bundle();
        bundle.putCharSequence("num", Integer.toString(index));
        it.putExtras(bundle);
        startActivity(it);
    }
}

接著是我們擦掉妹子衣服的頁(yè)面了,布局比較簡(jiǎn)單,F(xiàn)rameLayout + 前后兩個(gè)ImageView:

activity_caclothes.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/img_after"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <ImageView
        android:id="@+id/img_before"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</FrameLayout>

接著到就到Java部分的代碼了:

CaClothes.java

/**
 * Created by Jay on 2015/10/16 0016.
 */
public class CaClothes extends AppCompatActivity implements View.OnTouchListener {

    private ImageView img_after;
    private ImageView img_before;
    private Bitmap alterBitmap;
    private Canvas canvas;
    private Paint paint;
    private Bitmap after;
    private Bitmap before;
    private int position;

    int[] imageIds1 = new int[]
            {
                    R.mipmap.pre1, R.mipmap.pre2, R.mipmap.pre3, R.mipmap.pre4,
                    R.mipmap.pre5, R.mipmap.pre6, R.mipmap.pre7, R.mipmap.pre8,
                    R.mipmap.pre9, R.mipmap.pre10, R.mipmap.pre11, R.mipmap.pre12,
                    R.mipmap.pre13, R.mipmap.pre14, R.mipmap.pre15, R.mipmap.pre16,
                    R.mipmap.pre17, R.mipmap.pre18, R.mipmap.pre19, R.mipmap.pre20,
                    R.mipmap.pre21
            };

    int[] imageIds2 = new int[]
            {
                    R.mipmap.after1, R.mipmap.after2, R.mipmap.after3, R.mipmap.after4,
                    R.mipmap.after5, R.mipmap.after6, R.mipmap.after7, R.mipmap.after8,
                    R.mipmap.after9, R.mipmap.after10, R.mipmap.after11, R.mipmap.after12,
                    R.mipmap.after13, R.mipmap.after14, R.mipmap.after15, R.mipmap.after16,
                    R.mipmap.after17, R.mipmap.after18, R.mipmap.after19, R.mipmap.after20,
                    R.mipmap.after21
            };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_caclothes);

        Bundle bd = getIntent().getExtras();
        position = Integer.parseInt(bd.getString("num"));
        bindViews();

    }

    private void bindViews() {
        img_after = (ImageView) findViewById(R.id.img_after);
        img_before = (ImageView) findViewById(R.id.img_before);

        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inSampleSize = 1;
        after = BitmapFactory.decodeResource(getResources(), imageIds2[position], opts);
        before = BitmapFactory.decodeResource(getResources(), imageIds1[position], opts);
        //定義出來(lái)的是只讀圖片

        alterBitmap = Bitmap.createBitmap(before.getWidth(), before.getHeight(), Bitmap.Config.ARGB_4444);
        canvas = new Canvas(alterBitmap);
        paint = new Paint();
        paint.setStrokeCap(Paint.Cap.ROUND);
        paint.setStrokeJoin(Paint.Join.ROUND);
        paint.setStrokeWidth(5);
        paint.setColor(Color.BLACK);
        paint.setAntiAlias(true);
        canvas.drawBitmap(before, new Matrix(), paint);
        img_after.setImageBitmap(after);
        img_before.setImageBitmap(before);
        img_before.setOnTouchListener(this);
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                break;
            case MotionEvent.ACTION_MOVE:
                int newX = (int) event.getX();
                int newY = (int) event.getY();
                //setPixel方法是將某一個(gè)像素點(diǎn)設(shè)置成一個(gè)顏色,而這里我們把他設(shè)置成透明
                //另外通過(guò)嵌套for循環(huán)將手指觸摸區(qū)域的20*20個(gè)像素點(diǎn)設(shè)置為透明
                for (int i = -20; i < 20; i++) {
                    for (int j = -20; j < 20; j++) {
                        if (i + newX >= 0 && j + newY >= 0 && i + newX < before.getWidth() && j + newY < before.getHeight())
                            alterBitmap.setPixel(i + newX, j + newY, Color.TRANSPARENT);
                    }
                }
                img_before.setImageBitmap(alterBitmap);
                break;
        }
        return true;
    }
}

代碼也不算苦澀難懂,還是比較簡(jiǎn)單的哈,嗯,效果圖看看就好,別做那么多右手螺旋定則哈.... 


3.代碼示例下載:

DrawDemo1.zip 項(xiàng)目比較大,20多M,圖片資源比較多,你懂的~


本節(jié)小結(jié):

好的,本節(jié)寫(xiě)了關(guān)于繪圖的兩個(gè)小例子,還是蠻有趣的,相信你發(fā)下了,擦美女衣服那里, 消除的時(shí)候是方塊的,不那么完美是吧,沒(méi)事,下節(jié)我們學(xué)多個(gè)PorterDuff這個(gè)東西,我們 再來(lái)寫(xiě)多個(gè)例子,相比起這個(gè)代碼就簡(jiǎn)單很多了,另外,時(shí)間關(guān)系,代碼并沒(méi)有去優(yōu)化 或者整理,可以根據(jù)自己需求進(jìn)行修改~好的,就說(shuō)這么多,祝大家周末愉快~


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)