BitmapShader将图片转化为圆形图片

转载请注明出处,谢谢!

今天用BitmapShader实现圆形图片

package com.example.bitmap_porterduffxfermode;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Shader;
import android.util.AttributeSet;
import android.view.View;
import android.view.View.MeasureSpec;

public class RoundRectShaderView extends View {

	private int mMeasureHeigth;
	private int mMeasureWidth;

	private BitmapShader mBitmapShader;
	private Bitmap mBitmap;
	private Paint mPaint;

	public RoundRectShaderView(Context context) {
		super(context);
	}

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

	public RoundRectShaderView(Context context, AttributeSet attrs,
			int defStyleAttr) {
		super(context, attrs, defStyleAttr);
	}
	@Override
	protected void onMeasure(int widthMeasureSpec,
			int heightMeasureSpec) {
		mMeasureWidth = MeasureSpec.getSize(widthMeasureSpec);
		mMeasureHeigth = MeasureSpec.getSize(heightMeasureSpec);
		setMeasuredDimension(mMeasureWidth, mMeasureHeigth);

	}

	@Override
	protected void onDraw(Canvas canvas) {
		float length = 0;
		if (mMeasureHeigth >= mMeasureWidth) {
			length = mMeasureWidth;
		} else {
			length = mMeasureHeigth;
		}

		mBitmap = BitmapFactory.decodeResource(getResources(),
				R.drawable.zhongyu);
		mBitmapShader = new BitmapShader(mBitmap,
				Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);

		mPaint = new Paint();
		mPaint.setShader(mBitmapShader);
		canvas.drawCircle(length/2, length/2, length/2, mPaint);
	}
}



然后在布局文件中引用就行了

  <com.example.bitmap_porterduffxfermode.RoundRectShaderView
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:layout_gravity="center_horizontal" >
    </com.example.bitmap_porterduffxfermode.RoundRectShaderView>

测量一下View的高度,根据测量的高度设置遮罩层的大小,情况是这样,如果绘制的圆形小于图像大小,之会显示部分图像

弄清原理就明白了.

到底如何才能实现缩放图像大小呢?


解决方法:http://blog.csdn.net/wei_chong_chong/article/details/51125258


你可能感兴趣的:(BitmapShader将图片转化为圆形图片)