思维锻炼(ios球体):如何根据一个数组(成员是视图,有x,y,z属性)的数量,将一个数组近似平铺到一个球形视图上?

1:x向右为正方向,y向下为正方向,z向屏幕内为正方向,球的面向你那一点z为单位1(z,图层显示有用),球心z为三分之二,跟球心对称,不面向你的那一点z为三分之一;数组元素为n个,因为球是对称的,所以递增为单位一/n*2=2/n;其次,每元素的对应穿过球心的z轴圆偏移角度p,应为不确定质数的平方根,且小于0.5,大于0,取(3-根号5)*pai好了。

 

思路:首先求y,将球半径看为单位一,则每个视图y值为2/n X i - 1;

对应的平面圆(求z和x有用)r半径为:根号下1-y的平方.

x为r乘以cos(p*(3-根号5)*pai),z为sin(p*(3-根号5)*pai),

好了,每一点的坐标都拿到了,就可以平铺圆了

 

下边上一个代码例子、效果图:

//
//  ViewController.m
//  CollectionViewtest
//
//

#import "ViewController.h"
#import "MyCell.h"
#import "MyFlowLayout.h"
#import "CollectionViewtest-Swift.h"

@interface ViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>


@property(strong,nonatomic)UICollectionView *myCollectionView;
//球体
@property(assign,nonatomic)CGFloat velocity;
@property(assign,nonatomic)CGPoint last;
@property(strong,nonatomic)CADisplayLink *timer;
@property(strong,nonatomic)CADisplayLink *inertia;
@property(strong,nonatomic)NSMutableArray <UIButton*>*btns;
@property(strong,nonatomic)NSMutableArray <SpherePoint*>*coordinate;
@property(strong,nonatomic)SpherePoint *normalPoint;
@property(strong,nonatomic)NSMutableArray <UIButton*>*viewArr;
@property(strong,nonatomic)UIView *qiuBGV;;


@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    
    [self playView];
//    [self configCollectionView];
}
#pragma mark - 自定义folwlayout
-(void)configCollectionView{
    MyFlowLayout *flowLayout = [[MyFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(50, 50);
    flowLayout.minimumLineSpacing = 0;
    self.myCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 100, self.view.frame.size.width, 70) collectionViewLayout:flowLayout];
    self.myCollectionView.delegate = self;
    self.myCollectionView.dataSource = self;
    [self.myCollectionView registerClass:[MyCell class] forCellWithReuseIdentifier:@"MyCell"];
    [self.view addSubview:self.myCollectionView];
    self.myCollectionView.backgroundColor = [UIColor greenColor];
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
}
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return 100;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    MyCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MyCell" forIndexPath:indexPath];
    
    return cell;
}

#pragma mark - 球体布局
-(void)playView{
    UIView*view = [[UIView alloc] initWithFrame:CGRectMake(0, 100, self.view.frame.size.width, self.view.frame.size.width)];
    view.backgroundColor = [UIColor yellowColor];
    self.qiuBGV = view;
    [self.view addSubview:view];
    
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panWithGes:)];
    [view addGestureRecognizer:pan];
    
    self.viewArr = [[NSMutableArray alloc] initWithCapacity:0];
    self.coordinate = [NSMutableArray new];
    
    int sum = 50;
    CGFloat p1 = M_PI*(3-sqrt(5));
    CGFloat p2 = 2.0/sum;
    
    for (int i = 0; i<sum; i++) {
        UIButton *sView = [[UIButton alloc] initWithFrame:CGRectMake(view.frame.size.width/2.0, view.frame.size.height/2.0, 50, 50)];
        [sView setImage:[UIImage imageNamed:@"dog"] forState:UIControlStateNormal];
        
        
        CGFloat y = p2*i-1;
        CGFloat r = sqrt(1-y*y);
        CGFloat c = i*p1;
        CGFloat z = r*sin(c);
        CGFloat x = r*cos(c);
        
        sView.center = CGPointMake((x+1)*view.frame.size.width/2, (y+1)*view.frame.size.height/2);
        sView.layer.zPosition = z;
        sView.transform = CGAffineTransformScale(CGAffineTransformIdentity, (z+2)/3, (z+2)/3);
        
        SpherePoint *point = [[SpherePoint alloc] init:x :y :z];
        [self.coordinate addObject:point];
        
        [view addSubview:sView];
        [self.viewArr addObject:sView];
    }
    
    CGFloat a = (arc4random() % 10) - 5.0;
    CGFloat b= (arc4random() % 10) - 5.0;
    self.normalPoint = [[SpherePoint alloc] init:a :b :0];
    [self startAniamtion];
}
-(void)startAniamtion{
    self.timer = [CADisplayLink displayLinkWithTarget:self selector:@selector(autoTurnRotation)];
    [self.timer addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
}
-(void)autoTurnRotation{
    for (int i = 0; i<self.viewArr.count; i++) {
        [self updateSubviewsFrame:i direction:self.normalPoint angle:0.02];
    }
}
-(void)updateSubviewsFrame:(NSInteger)index direction:(SpherePoint*)direction angle:(CGFloat)angle {
    SpherePoint *point = self.coordinate[index];
    if (!point) {
        return;
    }
    SpherePoint *newPoint = [MatrixTool pointMakeRotationWithPoint:point direction:direction angle:angle];
    [self.coordinate replaceObjectAtIndex:index withObject:newPoint];
    [self setupSubview:newPoint index:index];
    
}
-(void)setupSubview:(SpherePoint*)point index:(NSInteger)index{
    UIButton* btn = self.viewArr[index];
    CGFloat x = (point.x + 1.0) * (self.qiuBGV.frame.size.width / 2.0);
    CGFloat y = (point.y + 1.0) * self.qiuBGV.frame.size.width / 2.0;
    btn.center = CGPointMake(x, y) ;
    
    CGFloat t = (point.z + 2.0) / 3.0;
    btn.transform = CGAffineTransformMakeScale(t, t);
    btn.layer.zPosition = t;
    btn.alpha = t;
    btn.userInteractionEnabled = (point.z>=0?YES:NO);
}
-(void)stopAniamtion{
    if (self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
}
-(void)inertiaStop{
    
    if (_inertia) {
        [_inertia invalidate];
        _inertia = nil;
    }
    [self startAniamtion];
}
-(void)panWithGes:(UIPanGestureRecognizer*)pan{
    if (pan.state == UIGestureRecognizerStateBegan) {
        self.last = [pan locationInView:self.qiuBGV];
        [self stopAniamtion];
        [self inertiaStop];
        
    } else if (pan.state == UIGestureRecognizerStateChanged) {
        CGPoint current = [pan locationInView:self.qiuBGV];
        SpherePoint *point = [[SpherePoint alloc] init:_last.y-current.y :current.x-_last.x :0];
        
        CGFloat distance = sqrtf(point.x*point.x+point.y*point.y);
        CGFloat angle = distance / (self.qiuBGV.frame.size.width / 2.0);
        NSInteger count = self.viewArr.count;
        if (count > 0) {
            for (int i = 0; i<count; i++) {
                [self updateSubviewsFrame:i direction:point angle:angle];
            }
            
        }
        self.normalPoint = point;
        self.last = current;
        
    } else if (pan.state == UIGestureRecognizerStateEnded){
        
        CGPoint vector = [pan velocityInView:self.qiuBGV];
        
        self.velocity = sqrt(vector.x*vector.x+vector.y*vector.y);
        
        
        [self inertiaStart];
    }
}
-(void)inertiaStart{
    [self stopAniamtion];
    self.inertia = [CADisplayLink displayLinkWithTarget:self selector:@selector(inertiaStep)];
    [self.inertia addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
}
-(void)inertiaStep{
    if (self.velocity<=0) {
        [self inertiaStop];
        return;
    }
    
    self.velocity = self.velocity - 70.0;
    CGFloat angle = self.velocity / self.qiuBGV.frame.size.width * 2.0 * (self.inertia.duration);
    for (int i = 0; i<self.viewArr.count; i++) {
        [self updateSubviewsFrame:i direction:self.normalPoint angle:angle];
    }
    
}
#pragma mark -
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end

球体旋转计算工具:

//
//  rotation.swift
//  CollectionViewtest
//
//

import Foundation
class Matrix: NSObject {
    var column: NSInteger
    var row: NSInteger
    var matrix: [[Float]]
    @objc init(_ c: NSInteger,
         _ r: NSInteger,
         _ mat: [[Float]] = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]) {
        column = c
        row = r
        matrix = mat
    }
}

class SpherePoint: NSObject {
    @objc var x: Float = 0.0
    @objc var y: Float = 0.0
    @objc var z: Float = 0.0
    
   @objc init(_ x: Float, _ y: Float, _ z: Float) {
        self.x = x
        self.y = y
        self.z = z
    }
}

class MatrixTool: NSObject {
    
        
        @objc public static func pointMakeRotation(point: SpherePoint, direction dir: SpherePoint, angle: Float) -> SpherePoint {
            guard angle != 0 else {
                return point
            }
            
            let t: [[Float]] = [[point.x, point.y, point.z, 1]]
            var result: Matrix = Matrix(1, 4, t)
            
            if dir.z * dir.z + dir.y * dir.y != 0 {
                let cos1: Float = dir.z / sqrt(dir.z * dir.z + dir.y * dir.y)
                let sin1: Float = dir.y / sqrt(dir.z * dir.z + dir.y * dir.y)
                let t1 = [[1, 0, 0, 0], [0, cos1, sin1, 0], [0, -sin1, cos1, 0], [0, 0, 0, 1]]
                let m1 = Matrix(4, 4, t1)
                result = matrixMutiply(a: result, b: m1)
            }
            
            if dir.x * dir.x + dir.y * dir.y + dir.z * dir.z != 0 {
                let cos2: Float = sqrt(dir.y * dir.y + dir.z * dir.z) / sqrt(dir.x * dir.x + dir.y * dir.y + dir.z * dir.z);
                let sin2: Float = -dir.x / sqrt(dir.x * dir.x + dir.y * dir.y + dir.z * dir.z)
                let t2 = [[cos2, 0, -sin2, 0], [0, 1, 0, 0], [sin2, 0, cos2, 0], [0, 0, 0, 1]]
                let m2 = Matrix(4, 4, t2)
                result = matrixMutiply(a: result, b: m2)
            }
            
            let cos3 = cos(angle)
            let sin3 = sin(angle)
            let t3 = [[cos3, sin3, 0, 0], [-sin3, cos3, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]
            let m3 = Matrix(4, 4, t3)
            result = matrixMutiply(a: result, b: m3)
            
            if dir.x * dir.x + dir.y * dir.y + dir.z * dir.z != 0 {
                let cos2 = sqrt(dir.y * dir.y + dir.z * dir.z) / sqrt(dir.x * dir.x + dir.y * dir.y + dir.z * dir.z)
                let sin2 = -dir.x / sqrt(dir.x * dir.x + dir.y * dir.y + dir.z * dir.z)
                let t2   = [[cos2, 0, sin2, 0], [0, 1, 0, 0], [-sin2, 0, cos2, 0], [0, 0, 0, 1]]
                let m2   = Matrix(4, 4, t2)
                result   = matrixMutiply(a: result, b: m2)
            }
            
            if dir.z * dir.z + dir.y * dir.y != 0 {
                let cos1 = dir.z / sqrt(dir.z * dir.z + dir.y * dir.y)
                let sin1 = dir.y / sqrt(dir.z * dir.z + dir.y * dir.y)
                let t1   = [[1, 0, 0, 0], [0, cos1, -sin1, 0], [0, sin1, cos1, 0], [0, 0, 0, 1]]
                let m1   = Matrix(4, 4, t1)
                result   = matrixMutiply(a: result, b: m1)
            }
            
            let resultPoint = SpherePoint(result.matrix[0][0], result.matrix[0][1], result.matrix[0][2])
            return resultPoint
        }
        
       @objc private static func matrixMutiply(a: Matrix, b: Matrix) -> Matrix {
            var matrix: Matrix = Matrix(a.column, b.row)
            for i in 0..<a.column {
                for j in 0..<b.row {
                    for k in 0..<a.row {
                        matrix.matrix[i][j] += a.matrix[i][k] * b.matrix[k][j]
                    }
                }
            }
            return matrix
        }

}

 

 

更多问题,欢迎加群讨论:565191947

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值