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

android只绘制一部分图片的解决方法

程序员文章站 2022-03-26 16:04:02
...

两种方法:

  1. canvas.drawBitmap(mBitmap, mSrcRect, mDestRect, mBitPaint);

  2. canvas.clipRect

package com.abilix.learn.dashpinyinisland1.view;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.util.AttributeSet;
import android.view.View;

import com.abilix.learn.dashpinyinisland1.R;


/**
 * yhd
 * 17.7.14
 */

public class DrawBitmapView extends View {
    private Resources mResources;
    private Paint mBitPaint;
    private Bitmap mBitmap;
    private Rect mSrcRect, mDestRect;

    // view 的宽高
    private int mTotalWidth, mTotalHeight;
    private int mBitWidth;
    private int mBitHeight;

    public DrawBitmapView(Context context) {
        this(context, null);
    }

    public DrawBitmapView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mResources = getResources();
        initBitmap();
        initPaint();
    }

    public DrawBitmapView(Context context, AttributeSet attrs, int defStyleAttr) {
        this(context, attrs);
    }

    private void initPaint() {
        mBitPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mBitPaint.setFilterBitmap(true);
        mBitPaint.setDither(true);
    }

    private void initBitmap() {
        mBitmap = ((BitmapDrawable) mResources.getDrawable(R.mipmap.sv_background_bright)).getBitmap();
        mBitWidth = mBitmap.getWidth();
        mBitHeight = mBitmap.getHeight();

        //方法一:选择绘画区域为下半图  选择绘画内容为下半图
        mSrcRect = new Rect(0, mBitHeight / 2, mBitWidth, mBitHeight);
        mDestRect = new Rect(0, mBitHeight / 2, mBitWidth, mBitHeight);


    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        //方法一:绘制
//        canvas.drawBitmap(mBitmap, mSrcRect, mDestRect, mBitPaint);

        //方法二:裁剪
        canvas.clipRect(0, mBitHeight/2, mBitWidth, mBitHeight);
        canvas.drawBitmap(mBitmap, 0, 0, mBitPaint);

    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mTotalWidth = w;
        mTotalHeight = h;
    }
}
相关标签: android 图片