自定义在图片上贴固定大小的图片

时间:2022-08-30 07:35:48
package com.wuzhou.corner.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.TextView;

import com.wuzhou.corner.R;

public class DefinedCardTextView extends TextView{
	Paint mPaint;
	Canvas mCanvas;
	Bitmap mBitmap;
    Bitmap mmBitmap;
	 
	@SuppressLint("NewApi")
	public DefinedCardTextView(Context context, AttributeSet attrs) {
		super(context, attrs);
		mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
		mPaint.setStyle(Paint.Style.STROKE);  
		mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.sfzyz_rili_img);
	}

	@SuppressLint("NewApi")
	@Override
	protected void onDraw(Canvas canvas) {
		// TODO Auto-generated method stub
		super.onDraw(canvas);
		mmBitmap = lessenBitmap(mBitmap, 30, 30);
		canvas.drawBitmap(mmBitmap, (float) (getWidth() - (mmBitmap.getWidth()*1.3)), (float) (this.getHeight() - (mmBitmap.getHeight()*1.3)), mPaint);
	}
	/**
     * lessen the bitmap
     *
     * @param src bitmap
     * @param destWidth the dest bitmap width
     * @param destHeigth
     * @return new bitmap if successful ,oherwise null
     */
    private Bitmap lessenBitmap( Bitmap src, int destWidth, int destHeigth )
    {
        String tag = "lessenBitmap";
        if( src == null )
        {
            return null;
        }
        int w = src.getWidth();//源文件的大小
        int h = src.getHeight();
        // calculate the scale - in this case = 0.4f
        float scaleWidth = ( ( float ) destWidth ) / w;//宽度缩小比例
        float scaleHeight = ( ( float ) destHeigth ) / h;//高度缩小比例
        Log.d( tag, "bitmap width is :" + w );
        Log.d( tag, "bitmap height is :" + h );
        Log.d( tag, "new width is :" + destWidth );
        Log.d( tag, "new height is :" + destHeigth );
        Log.d( tag, "scale width is  :" + scaleWidth );
        Log.d( tag, "scale height is  :" + scaleHeight );
        Matrix m = new Matrix();//矩阵
        m.postScale( scaleWidth, scaleHeight );//设置矩阵比例
        Bitmap resizedBitmap = Bitmap.createBitmap( src, 0, 0, w, h, m, true );//直接按照矩阵的比例把源文件画入进行
        return resizedBitmap;
    }

}

自定义在图片上贴固定大小的图片