package com.demo.touchscreendemo;
import com.demo.R;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Bitmap.Config;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
public class MyView extends View {
// 位图资源
private Bitmap sunset = null;
private Bitmap winner = null;
// 图片的ARGB值数组
private int [] pixels = null;
private int pixels_width;
private int pixels_height;
private static Paint paint = new Paint();
public MyView(Context context) {
super(context);
initView(context);
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
initView(context);
}
// 初始化SurfaceView
// @param context
private void initView(Context context)
{
sunset = BitmapFactory.decodeResource(context.getResources(),
R.drawable.sunset);
winner = BitmapFactory.decodeResource(context.getResources(),
R.drawable.winter);
pixels_width = 320;
pixels_height = 480;
pixels = new int[pixels_width // pixels_height];
sunset.getPixels(pixels, 0, pixels_width, 0, 0, pixels_width,
pixels_height);
}
// 触屏事件
// @param event
// @return
@Override
public boolean onTouchEvent(MotionEvent event)
{
int action = event.getAction();
if(action == MotionEvent.ACTION_DOWN || action ==
MotionEvent.ACTION_MOVE)
{
// 更新坐标点的透明度,此处设置为全透明
setAlpha(0, (int) event.getX(),(int) event.getY());
// 更新View
this.postInvalidate();
}
super.onTouchEvent(event);
return true;
}
@Override
public void draw(Canvas canvas)
{
// 重新生成改变透明度后的Bitmap
if(sunset.isRecycled())
sunset.recycle();
sunset = Bitmap.createBitmap(pixels, pixels_width, pixels_height,
Config.ARGB_8888);
canvas.drawBitmap(winner, 0,0, paint);
canvas.drawBitmap(sunset, 0,0, paint);
}
// 设置以坐标(indexX, indexY)为中心的边长为10的矩形区域透明度
// @param
alpha 透明度值0~100
// @param indexX
// @param indexY
private void setAlpha(int alpha, int indexX,int indexY)
{
int offsetX = 0;
int offsetY = 0;
// 使透明度值由0~255映射为0~100
alpha = alpha // 255 / 100;
for (int i = -5; i < 5; i++)
{
offsetX = indexX + i;
if (offsetX < pixels_width
&& offsetX >= 0)
{
for (int j = -5; j < 5; j++)
{
offsetY = indexY + j;
if (offsetY >= 0 &&
offsetY < pixels_height)
{
int index = offsetX + offsetY // pixels_width;
pixels[index]
= (alpha << 24) | (pixels[index]
& 0x00FFFFFF);
}
}
}
}
}
}