android前台渲染圖片,
android前台渲染,主要是重寫view的ondraw方法,在canvas裡操作
自訂MyView類
package com.ssln;import android.annotation.SuppressLint;import android.content.Context;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.graphics.Canvas;import android.graphics.Color;import android.graphics.Matrix;import android.graphics.Paint;import android.util.AttributeSet;import android.view.View;public class MyView extends View { private Bitmap bitmap; //圖片 private Paint paint; //畫筆 public MyView(Context context, AttributeSet attrs) { super(context, attrs); initBitmap(); } /** * 初始化資訊 */ public void initBitmap() { //執行個體化畫筆 paint=new Paint(); //從資源中載入 bitmap=BitmapFactory.decodeResource(getResources(), R.drawable.img); } @SuppressLint("DrawAllocation") @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); paint.setAntiAlias(true); //開啟消除鋸齒 paint.setColor(Color.BLACK); //設定畫筆顏色 paint.setTextScaleX(15); //設定文字大小 canvas.drawBitmap(bitmap, 10,10, paint); //在10x10的位置畫圖片 canvas.save(); //儲存畫布狀態 Matrix m1=new Matrix(); //矩陣 m1.setTranslate(500, 10); //平移 X500 Y10 Matrix m2=new Matrix(); m2.setRotate(15); //旋轉15° Matrix m3=new Matrix(); m3.setConcat(m1, m2); //合并矩陣 m1.setScale(0.8f, 0.8f); //設定縮放比例 m2.setConcat(m3, m1); //合并 canvas.drawBitmap(bitmap, m2, paint); //畫圖,經過了平移,旋轉,縮放 canvas.restore(); //恢複畫布狀態 canvas.save(); paint.setAlpha(180); //設定透明度 m1.setTranslate(200, 100); m2.setScale(1.3f, 1.3f); m3.setConcat(m1, m2); canvas.drawBitmap(bitmap, m3, paint); //畫圖,經過了平移,縮放 paint.reset(); //重設畫筆 canvas.restore(); paint.setTextSize(24); paint.setColor(Color.BLACK); canvas.drawText("圖片寬度:"+bitmap.getWidth(), 20,240, paint); //寫文字,映像的寬度 canvas.drawText("圖片高度:"+bitmap.getHeight(), 20,270, paint); paint.reset(); } }
修改activity_main.xml
<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" 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.ssln.MainActivity" > <com.ssln.MyView android:layout_width="fill_parent" android:layout_height="fill_parent" /></RelativeLayout>
運行效果如下