欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Android Canvas和Bitmap结合绘图详解流程

程序员文章站 2022-07-02 08:07:09
目录rect/rectfmatrixcanvasbitmaprect/rectf存储四个值的矩形类:左侧、顶部、右侧和底部。可用于直接在画布上绘制或仅用于存储要绘制的对象的大小。rect和rectf类...

rect/rectf

存储四个值的矩形类:左侧、顶部、右侧和底部。可用于直接在画布上绘制或仅用于存储要绘制的对象的大小。rect和rectf类之间的区别在于 rectf 存储浮点值,而rect类存储整数。

private static bitmap createdrawablebitmap(drawable drawable) {
    int width = drawable.getintrinsicwidth();
    int height = drawable.getintrinsicheight();
    if (width <= 0 || height <= 0) {
        return null;
    }
    float scale = math.min(1.0f, ((float) max_image_size) / ((float) (width * height)));
    if ((drawable instanceof bitmapdrawable) && scale == 1.0f) {
        return ((bitmapdrawable) drawable).getbitmap();
    }
    int bitmapwidth = (int) (((float) width) * scale);
    int bitmapheight = (int) (((float) height) * scale);
    bitmap bitmap = bitmap.createbitmap(bitmapwidth, bitmapheight, config.argb_8888);
    canvas canvas = new canvas(bitmap);
    rect existingbounds = drawable.getbounds();
    int left = existingbounds.left;
    int top = existingbounds.top;
    int right = existingbounds.right;
    int bottom = existingbounds.bottom;
    drawable.setbounds(0, 0, bitmapwidth, bitmapheight);
    drawable.draw(canvas);
    drawable.setbounds(left, top, right, bottom);
    return bitmap;
}

matrix

一个3 x 3的矩阵,用于存储可用于转换画布的信息。矩阵可以存储以下类型的变换信息:缩放、倾斜、旋转、平移。而每种变换方式都对应着三种方法:set方法将用新值替换当前的matrix,不管之前matrix的值是什么。pre和post 方法将在当前matrix包含的任何内容之前或之后应用新的转换。

matrix m = new matrix();
m.setrotate(90);
m.setscale(3f,1f);
m.settranslate(200, 200);

只有平移,旋转值和缩放值被重置

matrix m = new matrix();
m.prescale(3f,1f);
m.pretranslate(200f, 100f);
m.postscale(0.5f, 1f);
m.posttranslate(100f, 0f);

先进行平移(200f, 100f),然后进行缩放(3f, 1f),然后进行缩放(0.5f, 1f),最后进行平移(100f, 0f)

matrix m = new matrix();
m.posttranslate(200f, 0f);
m.prescale(0.5f, 1f);
m.setscale(1f, 1f);
m.postscale(5f, 1f);
m.pretranslate(200f, 100f);

先进行平移(200f, 100f),然后进行缩放(1f, 1f),最后进行缩放(5f, 1f)。因为用了set方法所以平移(200f, 0f)和缩放(0.5f, 1f)被覆盖,不起作用

假如先进行平移(x, y),再进行缩放(sx, sy),那么看到的平移效果等同于(x*sx, y*sy),因为缩放是将整个画布或者坐标系进行缩放的

canvas

canvas相当于android的画布,可以把画布想象成一块内存空间,也就是一个bitmap。canvas的api提供一整套在这个bitmap上进行绘图的操作方法。

  • drawbitmap(bitmap bitmap, matrix matrix, paint paint)

使用指定的矩阵绘制位图,绘制的时候会使用矩阵进行变换,矩阵和画笔可以传入空值

  • drawbitmap (bitmap bitmap, rect src, rect dst, paint paint)

将传入的源图bitmap指定的矩形区域src绘制到目标矩形区域dst中,如果矩形区域src传入空值,则表示绘制整个源图到目标矩形区域dst中,绘制的时候源图或子集自动缩放/平移以填充目标矩形。如果绘制对应的画笔通过方法setmaskfilter指定了超出原始位图宽/高的掩码过滤器(如blurmaskfilter),则会位图将继续被绘制,就像在具有clamp模式的着色器中一样。因此,原始宽/高之外的颜色将是复制的边缘颜色。因为源矩形区域src对应的坐标空间是相对于源图的,而目标矩形区域dst对应的坐标空间是绘制视图对应的坐标空间,因此要控制好对应的缩放因子。

  • drawbitmap (bitmap bitmap, rect src, rectf dst, paint paint)

矩阵示例:

bitmap background = bitmap.createbitmap((int)width, (int)height, config.argb_8888);
float originalwidth = originalimage.getwidth(); 
float originalheight = originalimage.getheight();

canvas canvas = new canvas(background);

float scale = width / originalwidth;

float xtranslation = 0.0f;
float ytranslation = (height - originalheight * scale) / 2.0f;

matrix transformation = new matrix();
transformation.posttranslate(xtranslation, ytranslation);
transformation.prescale(scale, scale);

paint paint = new paint();
paint.setfilterbitmap(true);

canvas.drawbitmap(originalimage, transformation, paint);

矩形区域示例:

public bitmap cropcircle(bitmap bitmap) {
  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());
  paint.setantialias(true);
  canvas.drawargb(0, 0, 0, 0);
  paint.setcolor(color);
  canvas.drawcircle(bitmap.getwidth() / 2, bitmap.getheight() / 2,
      bitmap.getwidth()/2, paint);
  paint.setxfermode(new porterduffxfermode(mode.src_in));
  canvas.drawbitmap(bitmap, rect, rect, paint);
  return output;
}

bitmap

位图,点阵图,可以理解为int[] buffer,用来存储每个像素点的容器。

  • bitmap.createbitmap(int width, int height, bitmap.config config)
  • bitmap.createbitmap(bitmap src)
  • bitmap.createbitmap(bitmap source, int x, int y, int width, int height)
  • bitmap.createbitmap(bitmap source, int x, int y, int width, int height,matrix m, boolean filter)
  • bitmapfactory.decodebytearray(byte[] data, int offset, int length, bitmapfactory.options opts)
  • bitmapfactory.decodefile(string pathname, options opts)
  • bitmapfactory.decodestream(inputstream is, rect outpadding,options opts)

createbitmap生成示例:

public bitmap transform(bitmap source) {
  int size = math.min(source.getwidth(), source.getheight());
  int x = (source.getwidth() - size) / 2;
  int y = (source.getheight() - size) / 2;
  bitmap squaredbitmap = bitmap.createbitmap(source, x, y, size, size);
  if (squaredbitmap != source) {
    source.recycle();
  }
  bitmap bitmap = bitmap.createbitmap(size, size, source.getconfig());
  canvas canvas = new canvas(bitmap);
  paint avatarpaint = new paint();
  bitmapshader shader = new bitmapshader(squaredbitmap, bitmapshader.tilemode.clamp, bitmapshader.tilemode.clamp);
  avatarpaint.setshader(shader);
  paint outlinepaint = new paint();
  outlinepaint.setcolor(color.white);
  outlinepaint.setstyle(paint.style.stroke);
  outlinepaint.setstrokewidth(stroke_width);
  outlinepaint.setantialias(true);
  float r = size / 2f;
  canvas.drawcircle(r, r, r, avatarpaint);
  canvas.drawcircle(r, r, r - stroke_width / 2, outlinepaint);
  squaredbitmap.recycle();
  return bitmap;
}

bitmapfactory生成示例:

private static bitmap decodesampledbitmapfromurl(string url, int reqwidth, int reqheight) throws ioexception {

	    // first decode with injustdecodebounds=true to check dimensions
	    final options options = new options();
	    options.injustdecodebounds = true;
	    
	    inputstream stream = fetchstream(url);
	    bitmapfactory.decodestream(stream, null, options);
	    stream.close();

	    // calculate insamplesize
	    options.insamplesize = calculateinsamplesize(options, reqwidth, reqheight);
	    // decode bitmap with insamplesize set
	    options.injustdecodebounds = false;
	    
	    stream = fetchstream(url);
	    bitmap bitmap = bitmapfactory.decodestream(stream, null, options);
	    stream.close();
	    
	    return bitmap;
	}
	
	private static inputstream fetchstream(string urlstring) throws illegalstateexception, ioexception {
		
		defaulthttpclient httpclient = new defaulthttpclient();
		httpget request = new httpget(urlstring);
		httpresponse response = httpclient.execute(request);
		return response.getentity().getcontent();
	}
	
	private static int calculateinsamplesize(options options, int reqwidth, int reqheight) {
		// raw height and width of image
		final int height = options.outheight;
		final int width = options.outwidth;
		int insamplesize = 1;

		if (height > reqheight || width > reqwidth) {

			// calculate ratios of height and width to requested height and width
			final int heightratio = math.round((float) height / (float) reqheight);
			final int widthratio = math.round((float) width / (float) reqwidth);

			// choose the smallest ratio as insamplesize value, this will guarantee
			// a final image with both dimensions larger than or equal to the
			// requested height and width.
			insamplesize = heightratio < widthratio ? heightratio : widthratio;
		}

		return insamplesize;
	}

注意:通过bitmap.createbitmap生成的bitmap对象是可变对象,可以向bitmap上绘制内容,而通过bitmapfactory生成的bitmap对象必须指定bitmapfactory.options.inmutable = true,否则就是不可变对象,不能向上面绘制内容。

感谢大家的支持,如有错误请指正,如需转载请标明原文出处!

到此这篇关于android canvas和bitmap结合绘图详解流程的文章就介绍到这了,更多相关android 绘图内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!