ios - UIBezierPath 矩形可以在所有方向上保持其位置吗?

标签 ios swift uibezierpath

对于横向和纵向模式,是否可以将元素重置到相同的%位置(距x = 0轴的距离)?如果是的话你能告诉我怎么做吗?另外,由于我是 Swift 的新手,如果您发现任何错误的代码错误,请DO通知我以便得到更好的帮助。提前致谢

这是我的ViewController:

import UIKit

    class ViewController: UIViewController
    {
        @IBOutlet var initView: UIView!
            {
                didSet
                {                
                    initView.addGestureRecognizer(UIPanGestureRecognizer(target: initView, action: "panRecognize:"))
                }
            }


    }

这是我的 View :

import UIKit

class InitView: UIView {



  private  struct location
    {
        static var movableRect : CGPoint = CGPoint.zero
        static var movableRectSize : CGSize = CGSize(width: location.screensize.width*0.2, height: location.screensize.height*0.05)
        static var screensize : CGRect = UIScreen.mainScreen().bounds
    }


    func panRecognize(gesture : UIPanGestureRecognizer)
    {
        let state = gesture.state
        switch state
        {
        case .Ended:
            fallthrough
        case .Changed:
            gesture.setTranslation(gesture.locationInView(self), inView: self)
            location.movableRect.x =    gesture.translationInView(self).x - location.movableRectSize.width/2
            location.movableRect.y =    gesture.translationInView(self).y - location.movableRectSize.height/2
            setNeedsDisplay()
        default:
            break
        }
    }

     private   func makeMovableRect(arg: CGPoint)
    {
        let path = UIBezierPath(rect: CGRect(origin: arg, size: location.movableRectSize))
        UIColor.purpleColor().set()
        path.fill()
    }

        override func drawRect(rect: CGRect)
    {

        if location.movableRect != CGPoint(x: 0, y: 0)
        {
            makeMovableRect(location.movableRect)

        }
    }

}

我的程序所做的只是在用户点击并保持按下的任何地方传输一个小矩形。当用户移除触摸屏幕时,该对象仍保留在最后一个位置(默认行为)。在我更改旋转后,因为边界发生了变化我希望它重绘到与肖像模式相同的位置。让我给你看一些照片来帮助你。也许这真的很简单,但在网上寻找解决方案让我尝试使用 UIDevice (isLandscape) 的 bool 值,但我有点把事情搞砸了。

Portrait Mode

What i want it to look like in landscape mode

最佳答案

您可以使用类似的函数

func pointForBounds(point: CGPoint,originalBounds: CGRect)->CGPoint{
        return CGPointMake(originalBounds.origin.x/self.bounds.origin.x*point.x, originalBounds.origin.y/self.bounds.origin.y*point.y)
    }

在 View 边界发生变化时更新矩形的原点

关于ios - UIBezierPath 矩形可以在所有方向上保持其位置吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33490609/

相关文章:

ios - PFQueryCollectionViewController 中首次加载时未出现图像

ios - 在不获取的情况下增加 CKRecord 变量中的字段值?

ios - 跨越新年时获取两个 NSDate 之间的天数

ios - 没有共享框架方案

iphone - 如何使用 UIBezierPath 在 Cocoa Touch 中绘制多边形

ios - Swift 3 和 XCode 8 : TextField bug in UIBezierPath

ios - 更改 tableview 的内容插图

ios - 有没有办法强制 ios 4 应用程序关闭并重新打开自己?

ios - RxSwift 如何将 "clear all"UIButton 添加到简单的电子表格示例

swift - iOS 用其他颜色填充 UIBezierPath 的一半而不使用 CAGradientLayer