自定义ImageView控件,根据重力感应,图片左右摇摆(只是类似于摇一摇的简单Demo。真机测试,不要用虚拟机,虚拟机没有重力感应。会有抖动现象,因为重力感应一直在变,可以参考下/detail/daweibalang717/6800609,请下载后自己完善)
下面是主代码:
public void setText(String text,float size){
this.text = text;
myPaint.setColor(Color.WHITE);
myPaint.setTextSize(size);
myPaint.setAntiAlias(true);//防止边缘的锯齿
myPaint.setFilterBitmap(true);//对位图进行滤波处理。
FontMetrics fm = myPaint.getFontMetrics(); //字体属性集
TextHeight = (float) Math.ceil(fm.descent - fm.top); //文字的高
float [] widths = new float[text.length()];
myPaint.getTextWidths(text, widths);
for (int i =0;i
TextWidth += widths[i];
}
}
public void setImage(int id){
bitmap = BitmapFactory.decodeResource(context.getResources(), id);
BufferBitmap = Bitmap.createBitmap(bitmap.getWidth()+width_padding, bitmap.getHeight()+height_padding, bitmap.getConfig());//因为要摆动,宽高增加一些
mCanvas = new Canvas(BufferBitmap);
isHavaeImage = true;
}
@Override
protected void onDraw(Canvas canvas)
{
// TODO Auto-generated method stub
super.onDraw(canvas);
}
@Override
public void doRotate(float x)
{
// TODO Auto-generated method stub
synchronized (this)
{
float degrees = (x / 10 )*90; // 求出角度。 x的重力加速度最大值为10 90度
System.out.println("偏角:"+ degrees);
matrix.postRotate(degrees-myDegress,BufferBitmap.getWidth()/2,0);
myDegress = degrees;
if(isHavaeImage && degrees>=-20.0 && degrees <=20.0){ //最大最小偏转度为20 -20;
clear(mCanvas);
mCanvas.setMatrix(matrix);
mCanvas.drawBitmap(bitmap,width_padding/2,0, myPaint);
mCanvas.drawText(text,(bitmap.getWidth()+width_padding-TextWidth)/2,bitmap.getHeight()/2+TextHeight, myPaint);//文字是以左下点为坐标的
setImageBitmap(BufferBitmap);//把缓存图形设置给Imageview;
invalidate();
}
}
}
public void clear(Canvas cancas){
Paint paint = new Paint();
paint.setXfermode(new PorterDuffXfermode(Mode.CLEAR));
cancas.drawPaint(paint);
}