android canvas 編輯bitmap畫虛線

銳湃發表於2015-09-01

效果圖



佈局檔案:

<LinearLayout 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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.testsss.PaintActivity" 
    android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />
    <Button 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="畫線"
        android:onClick="paint"/>
    <ImageView 
        android:id="@+id/iv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@drawable/ic_launcher"
        />

</LinearLayout>

activity

package com.example.testsss;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.PathEffect;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;

public class PaintActivity extends Activity {
    private ImageView iv;
    private Bitmap bitmap;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_paint);
		iv = (ImageView) findViewById(R.id.iv);
		bitmap = Bitmap.createBitmap(getResources().getDisplayMetrics().widthPixels,getResources().getDisplayMetrics().heightPixels-iv.getTop(), Config.ARGB_8888);
		
	}
	public void paint(View v){
		test();
	}
	private void test() {
		Canvas canvas = new Canvas(bitmap);
		Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
		p.setStyle(Style.STROKE);
		p.setColor(Color.BLUE);
		p.setStrokeWidth(5);
		PathEffect effects = new DashPathEffect(new float[] { 1, 2, 4, 8}, 1);
		p.setPathEffect(effects);
		canvas.drawCircle(getResources().getDisplayMetrics().widthPixels/2,getResources().getDisplayMetrics().widthPixels/2,
				getResources().getDisplayMetrics().widthPixels/3, p);
		canvas.drawLine(0, 0, getResources().getDisplayMetrics().widthPixels,getResources().getDisplayMetrics().widthPixels, p);
		iv.setImageBitmap(bitmap);
	} 
}


相關文章