重力感應,圖片擺動旋轉(自定義控制元件) android
阿新 • • 發佈:2019-02-04
自定義ImageView控制元件,根據重力感應,圖片左右搖擺(只是類似於搖一搖的簡單Demo。真機測試,不要用虛擬機器,虛擬機器沒有重力感應。會有抖動現象,因為重力感應一直在變,可以參考下http://download.csdn.net/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<widths.length;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); }