可调整大小的中心圆形UIView [英] Resizable Centered Circular UIView

查看:134
本文介绍了可调整大小的中心圆形UIView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法来创建一个CIRCULAR UIView ,它可以调整大小并保持居中(参见图像)。此示例中的CIRCULAR视图是 UIView 子类 WCSDailyGoal

I am looking for a way to create a CIRCULAR UIView that is resizable and stays centered (see image). The CIRCULAR view in this example is a UIView subclass WCSDailyGoal.

- (void)createDailyGoalView
{
    _dailyGoalView = [[WCSDailyGoalView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
    _dailyGoalView.delegate = self;
    _dailyGoalView.goal = 200;
    _dailyGoalView.center = self.view.center;
    [self.view addSubview:_dailyGoalView];
}



WCSDailyGoal.m



WCSDailyGoal.m

- (void)setGoal:(CGFloat)goal
{
    CGPoint saveCenter = self.center;
    CGRect newFrame = CGRectMake(self.frame.origin.x, self.frame.origin.y, goal, goal);
    self.frame = newFrame;
    self.layer.cornerRadius = goal / 2.0;
    self.center = saveCenter;
}

推荐答案

我能够通过制作自定义视图来实现此效果(以下代码是swift):

I was able to achieve this effect by making custom view (following code is in swift):

class ResizableCircleView: UIView {

   var maxSize: CGFloat = 100
   var minSize: CGFloat = 10

   private var dragRecognizer: UIPanGestureRecognizer!
   private var currentScale: CGFloat = 1

   private var defaultSize: CGFloat { return frame.width / currentScale }

   override func layoutSubviews() {
      super.layoutSubviews()
      if dragRecognizer == nil{
         dragRecognizer = UIPanGestureRecognizer(target: self, action: "handleDrag:")
         addGestureRecognizer(dragRecognizer)
      }
      backgroundColor = UIColor.blackColor()
      layer.cornerRadius = frame.width / 2
      clipsToBounds = true
   }

   func handleDrag(recognizer: UIPanGestureRecognizer){
      let inTopArea = recognizer.locationInView(self).y < frame.height / 2
      let dy = recognizer.translationInView(self).y

      var newSize = frame.height + (inTopArea ? -1 : 1) * dy
      newSize = min(maxSize, newSize)
      newSize = max(minSize, newSize)
      currentScale = newSize/defaultSize
      transform = CGAffineTransformMakeScale(currentScale, currentScale)

      recognizer.setTranslation(CGPointZero, inView: self)
   }
}

你可以调整通过将所需值设置为 maxSize minSize 来设置最大和最小尺寸。希望这会有所帮助。

You can adjust max and min sizes by setting desired values to maxSize and minSize. Hope this will help.

这篇关于可调整大小的中心圆形UIView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆