Android学习11-----多媒体技术(1) 绘制简单图形,Bitmap,Matrix

本文介绍如何在Android中自定义View类实现图形绘制,包括基本图形、Bitmap操作及使用Matrix进行图形变换的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

一、绘制简单图形

 

Android 中大部分的组件都是 View 的子类,而如果要想进行图形的绘制操作,则可以直接使用一个类继承 View 类,之后覆写 View 类中的指定方法。

· protected void onDraw(Canvas canvas)

         在之前编写图形界面的时候,都是使用一个个的图形组件,那么这些组件都是一个 View 的子类,可是很多时候需要用户自己构图,例如,在做游戏的时候,这些图形基本上都是没有的。

下面给一个范例:

MyView.java

package com.iflytek.demo;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Rect;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;

/**
 * @author xdwang
 * 
 * @create 2012-11-11 下午9:19:17
 * 
 * @email:xdwangiflytek@gmail.com
 * 
 * @description 自定义组件
 * 
 */
public class MyView extends View {
	public MyView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	@Override
	protected void onDraw(Canvas canvas) {
		canvas.drawColor(Color.WHITE); // 设置背景为白色
		Paint paint = new Paint();

		// ------------1、圆形-----------------
		paint.setColor(Color.BLUE); // 设置图形的底色
		canvas.drawCircle(30, 50, 25, paint);// 从30,50为原点,25为半径画原型

		// ------------2、矩形-----------------
		paint.setColor(Color.BLACK);
		canvas.drawRect(80, 20, 160, 80, paint);

		// ------------3、RECT绘制空心矩形-----------------
		Rect rect = new Rect(); // 定义矩形
		rect.set(180, 20, 300, 80);
		paint.setStyle(Style.STROKE);// 设置空心的
		canvas.drawRect(rect, paint);

		// ------------4、绘制文字-----------------
		paint.setColor(Color.RED);
		paint.setTextSize(20);
		canvas.drawText("xdwangiflytek", 40, 110, paint);

		// ------------5、绘制直线-----------------
		paint.setColor(Color.BLACK);
		canvas.drawLine(10, 120, 300, 120, paint);

		// ------------6、绘制空心椭圆-----------------
		RectF oval = new RectF();
		oval.set(10.0f, 140.0f, 110.0f, 200.0f);
		canvas.drawOval(oval, paint);

		// ------------7、绘制空心扇形-----------------
		oval = new RectF();
		oval.set(150.0f, 140.0f, 210.0f, 200.0f);
		canvas.drawArc(oval, 150.0f, 140.0f, true, paint);

	}
}

 

main.xml

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

    <com.iflytek.demo.MyView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

</LinearLayout>
 

效果图

 

 

二、 Bitmap

 

         Android.graphics.Bitmap (位图)是 Android 手机中专门提供的用于操作图片资源的操作类,使用此类可以直接从资源文件之中进行图片资源的读取,并且对这些图片进行一些简单的修改。

Bitmap 类的常用方法:

No.

方法

描述

1

Public static Bitmap createBitmap(Bitmap src)

复制一个 Bitmap

2

Public static Bitmap createBitmap(Bitmap source,int x,int y,int width,int height,Matrix m,Boolean filter)

对一个 Bitmap 进行剪切

3

Public final int getHeight()

取得图像的高

4

Public final int getWidth()

取得图像的宽

5

Public static Bitmap createScaledBitmap(Bitmap src,int dstWidth,int dstHeight,boolean filter)

创建一个指定大小的 Bitmap

 

如果要想通过资源文件取得一个 Bitmap 实例,则需要 android.graphics.BitmapFactory 类支持。其方法有:

No.

方法

描述

1

Public static Bitmap decodeByteArray(byte[] data,int offset,int length)

根据指定的数据文件创建 Bitmap

2

Public static Bitmap decodeFile(String pathName)

根据 指定的路径创建 Bitmap

3

Public static Bitmap decodeResource(resources res,int id)

根据指定的资源创建 Bitmap

4

Public static Bitmap decodeStream(InputStream is)

根据指定的 InputStream 创建 Bitmap

 

范例 MyView.java

package com.iflytek.demo;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;

/**
 * @author xdwang
 * 
 * @create 2012-11-11 下午10:09:44
 * 
 * @email:xdwangiflytek@gmail.com
 * 
 * @description 自定义组件
 * 
 */
public class MyView extends View {

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

	@Override
	protected void onDraw(Canvas canvas) {

		// ------------------1、基本绘图---------------------
//		Bitmap bitmap = BitmapFactory.decodeResource(super.getResources(),
//				R.drawable.ic_launcher); // 找到图片的Bitmap对象
//		Paint paint = new Paint();
//		paint.setAntiAlias(true); // 消除锯齿
//		canvas.drawBitmap(bitmap, 0, 0, paint);
//		paint.setColor(Color.WHITE); // 底色
//		paint.setTextSize(20);
//		canvas.drawText(
//				"图片高度:" + bitmap.getHeight() + ",图片宽度:" + bitmap.getWidth(),
//				10, bitmap.getHeight() + 20, paint);

		// ------------------2、填充桌面---------------------
//		DisplayMetrics dm = super.getResources().getDisplayMetrics();
//		int screenWidth = dm.widthPixels;
//		int screenHeight = dm.heightPixels;
//		Bitmap bitmap = BitmapFactory.decodeResource(super.getResources(),
//				R.drawable.ic_launcher); // 找到图片的Bitmap对象
//		bitmap = Bitmap.createScaledBitmap(bitmap, screenWidth, screenHeight,
//				true);
//		Paint paint = new Paint();
//		paint.setAntiAlias(true); // 消除锯齿
//		canvas.drawBitmap(bitmap, 0, 0, paint);

		// ------------------3、指定位置区域显示---------------------
//		Bitmap bitmap = BitmapFactory.decodeResource(super.getResources(),
//				R.drawable.ic_launcher);	// 找到图片的Bitmap对象
//		Paint paint = new Paint() ;
//		paint.setAntiAlias(true); // 消除锯齿
//		canvas.drawBitmap(bitmap, null, new Rect(30, 50, 200, 200), paint);
		
		// ------------------4、图片剪贴---------------------
		Bitmap bitmap = BitmapFactory.decodeResource(super.getResources(),
				R.drawable.ic_launcher);	// 找到图片的Bitmap对象
		Paint paint = new Paint() ;
		paint.setAntiAlias(true); // 消除锯齿
		canvas.drawBitmap(bitmap, new Rect(10,10,20,20), new Rect(10, 10, 20, 20), paint); 
	}
}

 

Bitmap 最大的特点是可以操作我的二进制数据

 

三、 Matrix

         使用 Bitmap 可以进行图形的绘制,但是如果希望图形可以进行一些平移、旋转、缩放、倾斜等变换的话,则需要使用 android.graphics.Matrix 类(矩阵)的支持。

package com.iflytek.demo;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.util.AttributeSet;
import android.view.View;

/**
 * @author xdwang
 * 
 * @create 2012-11-11 下午10:22:24
 * 
 * @email:xdwangiflytek@gmail.com
 * 
 * @description 自定义组件
 * 
 */
public class MyView extends View {
	private Bitmap bitmap = null;
	private Matrix matrix = new Matrix();

	public MyView(Context context, AttributeSet attrs) {
		super(context, attrs);
		this.bitmap = BitmapFactory.decodeResource(super.getResources(),
				R.drawable.ic_launcher);
		
//		float cosValue = (float) Math.cos(-Math.PI / 3);
//		float sinValue = (float) Math.sin(-Math.PI / 3);
//		this.matrix.setValues(new float[] { cosValue, -sinValue, 100, sinValue,
//				cosValue, 200, 0, 0, 2 });
		
		this.matrix.preScale(0.5f, 0.5f, 50, 100);
		this.matrix.preRotate(-60, 50, 100);
		this.matrix.preTranslate(50, 100) ;
	}

	@Override
	protected void onDraw(Canvas canvas) {
		canvas.drawBitmap(this.bitmap, this.matrix, null);
	}

}

 

android Bitmap用法总结 Bitmap用法总结 1、Drawable → Bitmap public static Bitmap drawableToBitmap(Drawable drawable) { Bitmap bitmap = Bitmap .createBitmap( drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565); Canvas canvas = new Canvas(bitmap); // canvas.setBitmap(bitmap); drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight()); drawable.draw(canvas); return bitmap; } 2、从资源中获取Bitmap Resources res=getResources(); Bitmap bmp=BitmapFactory.decodeResource(res, R.drawable.pic); 3、Bitmap → byte[] private byte[] Bitmap2Bytes(Bitmap bm){ ByteArrayOutputStream baos = new ByteArrayOutputStream(); bm.compress(Bitmap.CompressFormat.PNG, 100, baos); return baos.toByteArray(); } 4、byte[] → Bitmap private Bitmap Bytes2Bimap(byte[] b){ if(b.length!=0){ return BitmapFactory.decodeByteArray(b, 0, b.length); } else { return null; } } 5、保存bitmap static boolean saveBitmap2file(Bitmap bmp,String filename){ CompressFormat format= Bitmap.CompressFormat.JPEG; int quality = 100; OutputStream stream = null; try { stream = new FileOutputStream("/sdcard/" + filename); } catch (FileNotFoundException e) { // TODO Auto-generated catch block Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. e.printStackTrace(); } return bmp.compress(format, quality, stream); } 6、将图片按自己的要求缩放 // 图片源 Bitmap bm = BitmapFactory.decodeStream(getResources() .openRawResource(R.drawable.dog)); // 获得图片的宽高 int width = bm.getWidth(); int height = bm.getHeight(); // 设置想要的大小 int newWidth = 320; int newHeight = 480; // 计算缩放比例 float scaleWidth = ((float) newWidth) / width; float scaleHeight = ((float) newHeight) / height; // 取得想要缩放的matrix参数 Matrix matrix = new Matrix(); matrix.postScale(scaleWidth, scaleHeight); // 得到新的图片 Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true); // 放在画布上 canvas.drawBitmap(newbm, 0, 0, paint); 相关知识链接:http://www.eoeandroid.com/thread-3162-1-1.html 7、bitmap的用法小结 BitmapFactory.Options option = new BitmapFactory.Options(); option.inSampleSize = 2; //将图片设为原来宽高的1/2,防止内存溢出 Bitmap bm = BitmapFactory.decodeFile("",option);//文件流 URL url = new URL(""); InputStream is = url.openStream(); Bitmap bm = BitmapFactory.decodeStream(is); android:scaleType: android:scaleType是控制图片如何resized/moved来匹对ImageView的size。ImageView.ScaleType / android:scaleType值的意义区别: CENTER /center 按图片的原来size居中显示,当图片长/宽超过View的长/宽,则截取图片的居中部分 显示 CENTER_CROP / centerCrop 按比例扩大图片的size居中显示,使得图片长()等于或大于View的长 () CENTER_INSIDE / centerInside 将图片的内容完整居中显示,通过按比例缩小或原来的size使得图片 长/宽等于或小于View的长/宽 Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. FIT_CENTER / fitCenter 把图片按比例扩大/缩小到View的宽度,居中显示 FIT_END / fitEnd 把图片按比例扩大/缩小到View的宽度,显示在View的下部分位置 FIT_START / fitStart 把图片按比例扩大/缩小到View的宽度,显示在View的上部分位置 FIT_XY / fitXY 把图片 不按比例 扩大/缩小到View的大小显示 MATRIX / matrix 用矩阵来绘制,动态缩小放大图片来显示。 //放大缩小图片 public static Bitmap zoomBitmap(Bitmap bitmap,int w,int h){ int width = bitmap.getWidth(); int height = bitmap.getHeight(); Matrix matrix = new Matrix(); float scaleWidht = ((float)w / width); float scaleHeight = ((float)h / height); matrix.postScale(scaleWidht, scaleHeight); Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true); return newbmp; } //将Drawable转化为Bitmap public static Bitmap drawableToBitmap(Drawable drawable){ int width = drawable.getIntrinsicWidth(); int height = drawable.getIntrinsicHeight(); Bitmap bitmap = Bitmap.createBitmap(width, height, drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565); Canvas canvas = new Canvas(bitmap); drawable.setBounds(0,0,width,height); drawable.draw(canvas); return bitmap; Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. } //获得圆角图片的方法 public static Bitmap getRoundedCornerBitmap(Bitmap bitmap,float roundPx){ Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap .getHeight(), Config.ARGB_8888); Canvas canvas = new Canvas(output); final int color = 0xff424242; final Paint paint = new Paint(); final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()); final RectF rectF = new RectF(rect); paint.setAntiAlias(true); canvas.drawARGB(0, 0, 0, 0); paint.setColor(color); canvas.drawRoundRect(rectF, roundPx, roundPx, paint); paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN)); canvas.drawBitmap(bitmap, rect, rect, paint); return output; } //获得带倒影的图片方法 public static Bitmap createReflectionImageWithOrigin(Bitmap bitmap){ final int reflectionGap = 4; int width = bitmap.getWidth(); int height = bitmap.getHeight(); Matrix matrix = new Matrix(); matrix.preScale(1, -1); Bitmap reflectionImage = Bitmap.createBitmap(bitmap, 0, height/2, width, height/2, matrix, false); Bitmap bitmapWithReflection = Bitmap.createBitmap(width, (height + height/2), Config.ARGB_8888); Canvas canvas = new Canvas(bitmapWithReflection); canvas.drawBitmap(bitmap, 0, 0, null); Paint deafalutPaint = new Paint(); Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. canvas.drawRect(0, height,width,height + reflectionGap, deafalutPaint); canvas.drawBitmap(reflectionImage, 0, height + reflectionGap, null); Paint paint = new Paint(); LinearGradient shader = new LinearGradient(0, bitmap.getHeight(), 0, bitmapWithReflection.getHeight() + reflectionGap, 0x70ffffff, 0x00ffffff, TileMode.CLAMP); paint.setShader(shader); // Set the Transfer mode to be porter duff and destination in paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN)); // Draw a rectangle using the paint with our linear gradient canvas.drawRect(0, height, width, bitmapWithReflection.getHeight() + reflectionGap, paint); return bitmapWithReflection; } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值