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>
运行效果如下
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。