望远镜效果

package com.loaderman.customviewdemo;

import android.content.Context;
import android.graphics.*;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;


public class TelescopeView extends View {
    private Paint mPaint;
    private Bitmap mBitmap,mBitmapBG;
    private int mDx = -1, mDy = -1;

    public TelescopeView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mPaint = new Paint();
        mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.scenery);
    }

    @Override
public boolean onTouchEvent(MotionEvent event) {
    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            mDx = (int) event.getX();
            mDy = (int) event.getY();
            postInvalidate();
            return true;
        case MotionEvent.ACTION_MOVE:
            mDx = (int) event.getX();
            mDy = (int) event.getY();
            break;
        case MotionEvent.ACTION_UP:
        case MotionEvent.ACTION_CANCEL:
            mDx = -1;
            mDy = -1;
            break;
    }
    postInvalidate();
    return super.onTouchEvent(event);
}

    @Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    if (mBitmapBG == null){
        mBitmapBG = Bitmap.createBitmap(getWidth(),getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvasbg = new Canvas(mBitmapBG);
        canvasbg.drawBitmap(mBitmap,null,new Rect(0,0,getWidth(),getHeight()),mPaint);
    }

    if (mDx != -1 && mDy != -1) {
        /*
        setShader函数给空白图片上色,相等于pS中的印章工具
        * */
        mPaint.setShader(new BitmapShader(mBitmapBG, Shader.TileMode.REPEAT, Shader.TileMode.REPEAT));
        canvas.drawCircle(mDx, mDy, 150, mPaint);
    }
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_gravity="center"
    android:gravity="center"
    android:background="@android:color/white"
    >
 <TextView
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:text="点击空白有惊喜"
     android:textSize="24dp"
     android:textColor="#ff0000"/>

 <com.loaderman.customviewdemo.TelescopeView
     android:layout_width="match_parent"
     android:layout_height="match_parent" />
</LinearLayout>

效果:

 

posted on 2019-01-03 10:47  LoaderMan  阅读(160)  评论(0编辑  收藏  举报

导航