本文介绍了在bitmap上绘制三种图形,分别是:画线、写文本、画上原本存在 的图片
首先写好布局,代码如下
<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"> <LinearLayout android:layout_width="300dp" android:layout_height="350dp" android:layout_centerInParent="true"> <ImageView android:id="@+id/id_iv_1" android:layout_width="match_parent" android:layout_height="match_parent"/> </LinearLayout> <Button android:id="@+id/id_bt1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:text="点我"/> </RelativeLayout>
第二步,自定义一个工具类Mydraw包含三种方法drawLine(),drawText\(),drawPic(),从字面上很容易理解分别是:画线,写字,画图,代码如下:
public class Mydraw { static Bitmap mBitmap; public static void drawLine(ImageView view){ int height=view.getHeight(); int width=view.getWidth(); mBitmap=Bitmap.createBitmap(width,height,Config.ARGB_8888); Canvas mCanvas=new Canvas(mBitmap); Paint mPaint=new Paint(); mPaint.setColor(Color.parseColor("#7B7B7B")); mPaint.setStyle(Style.STROKE); mPaint.setStrokeWidth(5); mCanvas.drawLine(0, 0, width ,0 , mPaint); mCanvas.drawLine(width, 0, width ,height , mPaint); mCanvas.drawLine(0, 0, 0 ,height , mPaint); mCanvas.drawLine(0, height, width, height, mPaint); view.setImageBitmap(mBitmap); } public static void drawText(ImageView view){ String mText="solo你好"; Rect mRect=new Rect(); int width=view.getWidth(); int height=view.getHeight(); Canvas mCanvas=new Canvas(mBitmap); Paint mPaint=new Paint(); mPaint.setColor(Color.RED); mPaint.setTextSize(40); mPaint.getTextBounds(mText, 0, mText.length(), mRect); mCanvas.drawText(mText, width/2-mRect.width()/2,height/2+mRect.height()/2, mPaint); view.setImageBitmap(mBitmap); } public static void drawPic(ImageView view,Resources res){ Bitmap bm=BitmapFactory.decodeResource(res,R.drawable.ic_launcher); int width=view.getWidth(); int height=view.getHeight(); Canvas mCanvas=new Canvas(mBitmap); mCanvas.drawBitmap(bm, width/2-bm.getWidth()/2, 0, null); view.setImageBitmap(mBitmap); } }
public class MainActivity extends Activity implements OnClickListener { private ImageView mImageView; private Button mButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mImageView=(ImageView) findViewById(R.id.id_iv_1); mButton=(Button)findViewById(R.id.id_bt1); mButton.setOnClickListener(this); } //由于不能再onCreate()中直接测量view的宽和高,所以我们这里在button的点击事件中去执行这些测量 @Override public void onClick(View v) { Mydraw.drawLine(mImageView); Mydraw.drawText(mImageView); Mydraw.drawPic(mImageView, getResources()); } }