欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Android自定義View圓形和拖動圓、跟隨手指拖動效果

 更新時間:2017年09月18日 09:06:42   作者:贏le  
單純的自定義一個圓非常簡單 只需要幾步就完成 拖動圓添加實(shí)現(xiàn)觸摸事件即可 。接下來通過本文給大家分享Android自定義View圓形和拖動圓、跟隨手指拖動效果,感興趣的朋友一起看看吧

單純的自定義一個圓非常簡單 只需要幾步就完成 拖動圓添加實(shí)現(xiàn)觸摸事件即可

我在第一次自定義View圓遇到的幾個Bug:

1.拖動圓的話在xml里面設(shè)置的自定義圓的寬和高是它能活動的空間的大小 不是圓控件的大小 如果你定義了100dp 拖動它的時候超過100dp這個距離這個圓就會看不見 就像下面這樣 如果想活動于整個屏幕直接給寬和高match_parent屬性就好了

這里寫圖片描述

2.我在定義充滿屬性match_parent的時候運(yùn)行會報錯,什么方法都用了就是不行,耐心等待過一會就好了…有可能是studio沒來得及編譯過來

下面開始寫代碼: 先是單純的創(chuàng)建一個圓形 創(chuàng)建一個類繼承View 實(shí)現(xiàn)onDraw方法

public class CustomView extends View {
 //創(chuàng)建point對象 參數(shù)為x坐標(biāo)和y坐標(biāo)
 private PointF point = new PointF(100, 100);
 public CustomView(Context context) {
  super(context);
 }
 public CustomView(Context context, @Nullable AttributeSet attrs) {
  super(context, attrs);
 }
 public CustomView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
  super(context, attrs, defStyleAttr);
 }
 @Override
 protected void onDraw(Canvas canvas) {
  super.onDraw(canvas);
  //參數(shù)為圓的橫坐標(biāo) ,縱坐標(biāo),半徑,創(chuàng)建
  canvas.drawCircle(point.x,point.y, 50, new Paint());
 }
}

XML里、自己定義的view類的名字:

<ydtx.bwie.com.xiangmu_project02.CustomView
  android:layout_width="match_parent"
  android:layout_height="match_parent" />

一個圓就這樣創(chuàng)建好了 直接運(yùn)行就可以了 ManActivity里什么也不用改

@Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
 }

下面是添加拖動圓的功能 非常簡單 實(shí)現(xiàn)觸摸監(jiān)聽即可 代碼非常少 如下:

public class CustomView extends View {
 //創(chuàng)建point對象 參數(shù)為x坐標(biāo)和y坐標(biāo)
 private PointF point = new PointF(100, 100);
 public CustomView(Context context) {
  super(context);
 }
 public CustomView(Context context, @Nullable AttributeSet attrs) {
  super(context, attrs);
 }
 public CustomView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
  super(context, attrs, defStyleAttr);
 }
 @Override
 protected void onDraw(Canvas canvas) {
  super.onDraw(canvas);
  //參數(shù)為圓的橫坐標(biāo) ,縱坐標(biāo),半徑,創(chuàng)建 
  canvas.drawCircle(point.x,point.y, 50, new Paint());
 }
 //觸摸事件
 @Override
 public boolean onTouchEvent(MotionEvent event) {
  //獲得觸摸事件
  switch (event.getAction()) {
   case MotionEvent.ACTION_DOWN:
    break;
   //ACTION_MOVE不要設(shè)置break,否則圓形不會跟隨手指活動 只會手指松開屏幕的時候圓形直接到了屏幕停止的位置
   case MotionEvent.ACTION_MOVE:
   case MotionEvent.ACTION_UP:
    //獲取手指觸摸位置的x坐標(biāo)
    point.x = event.getX();
    //獲取手指觸摸位置的y坐標(biāo)
    point.y = event.getY();
    //啟動
    postInvalidate();
    break;
  }
  return true;
 }
}

總結(jié)

以上所述是小編給大家介紹的Android自定義View圓形和拖動圓、跟隨手指拖動效果,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!

相關(guān)文章

最新評論