大体思路,首先Bitmap.createBitmap创建位图,然后自定义函数drawIntoBitmap,最后通过onDraw创建画布来实现绘制的位图
package com.example;
import java.io.InputStream;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Shader;
import android.os.Bundle;
import android.view.View;
public class AlphaBitmapActivity extends Activity {
public Bitmap mBitmap1, mBitmap2, mBitmap3;
public Shader mShader;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new SampleView(this));
}
public class SampleView extends View {
public SampleView(Context context) {
super(context);
setFocusable(true); //控件允许获取焦点
InputStream is = context.getResources().openRawResource(R.drawable.sample);
mBitmap1 = Bitmap.createBitmap(200, 200, Bitmap.Config.ALPHA_8);
drawIntoBitmap(mBitmap3、1);
/*生成 LinearGradient对象
new LinearGradien(0,0,100,100,Color.RED,Color.BLUE,Shader.TileMode.MIRROR);
参数一:为渐变起点坐标的x轴位置,
参数二 :为渐变起点坐标的y轴位置,
参数三 :为渐变终点坐标的x轴位置,
参数四 :为渐变终点坐标的y轴位置,
参数五 :平铺方式,这里设置为镜像
*/
mShader = new LinearGradient(0, 0, 300, 500, new int[] {
Color.RED, Color.GREEN, Color.BLUE}, null, Shader.TileMode.MIRROR);
}
/*绘制位图*/
public void drawIntoBitmap(Bitmap bm) {
float x = bm.getWidth();
float y = bm.getHeight();
Canvas c = new Canvas(bm);
Paint p = new Paint();
p.setAntiAlias(true);
p.setAlpha(0x80);
c.drawCircle(x/2, y/2, x/2, p);
p.setAlpha(0x80);
p.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC));
p.setTextSize(60);
p.setTextAlign(Paint.Align.CENTER);
Paint.FontMetrics fm = p.getFontMetrics();
c.drawText("Alpha", x/2, y/2-fm.ascent/2, p); //"Alpha"字符串在绘制的圆形中的文字
}
public void onDraw(Canvas canvas) {
canvas.drawColor(Color.WHITE); //画布底色设为白色
Paint p = new Paint();
p.setColor(Color.RED); //设置文字颜色
p.setTextSize(36); //设置文字大小
p.setShader(mShader); //设置图像阴影效果
canvas.drawBitmap(mBitmap1, bw, bh, p);
/*得到画布宽度高度*/
float cw= canvas.getWidth();
float ch = canvas.getHeight();
canvas.drawText("宽度 "+cw+" 高度 "+ ch, 50, 50, p);
}
}
}
结果如图
另外说明的是 注意canvas.drawText()和canvas.drawBitmap()
drawText(String text, float x, float y, Paint paint) 中x,y是从字符串的左下角开始,y是字符串的baseline
drawBitmap(Bitmap bitmap, float left, float top, Paint paint)中x,y是生成位图的左上角的点到画布左边和上边的距离