一. 開發按照設計出的UI進行開發,效果圖如下:
WechatIMG1031.jpg
二.看背景是一個平行四邊形且帶有圓角,我就直接上代碼了
1.新建FYParallelogramView
類繼承UIView
.h
文件:
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface FYParallelogramView : UIView
@property (nonatomic, assign) CGFloat offset; // 頂邊偏移量,控制傾斜
@property (nonatomic, assign) CGFloat cornerRadius; // 邊角弧度
@property (nonatomic, strong) UIColor *fillColor; // 填充顏色
@end
NS_ASSUME_NONNULL_END
.m
文件:
#import "FYParallelogramView.h"
@implementation FYParallelogramView
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
_offset = 0.0;
_cornerRadius = 0.0;
_fillColor = [UIColor blueColor];
}
return self;
}
- (void)drawRect:(CGRect)rect {
[super drawRect:rect];
[super drawRect:rect];
CGFloat width = CGRectGetWidth(rect);
CGFloat height = CGRectGetHeight(rect);
CGPoint topLeft = CGPointMake(_offset, 0);
CGPoint topRight = CGPointMake(width, 0);
CGPoint bottomRight = CGPointMake(width - _offset, height);
CGPoint bottomLeft = CGPointMake(0, height);
// 計算相鄰邊的向量長度
CGFloat edgeLength = sqrt(pow(_offset, 2) + pow(height, 2));
if (edgeLength == 0) return; // 避免除零
// 單位向量(左邊和右邊)
CGFloat leftUnitX = -_offset / edgeLength;
CGFloat leftUnitY = height / edgeLength;
CGFloat rightUnitX = -_offset / edgeLength;
CGFloat rightUnitY = height / edgeLength;
// 計算圓角截取點
CGPoint A = CGPointMake(topLeft.x + _cornerRadius, topLeft.y);
CGPoint B = CGPointMake(topLeft.x + leftUnitX * _cornerRadius, topLeft.y + leftUnitY * _cornerRadius);
CGPoint C = CGPointMake(topRight.x - _cornerRadius, topRight.y);
CGPoint D = CGPointMake(topRight.x + rightUnitX * _cornerRadius, topRight.y + rightUnitY * _cornerRadius);
CGPoint E = CGPointMake(bottomRight.x + (-rightUnitX) * _cornerRadius, bottomRight.y + (-rightUnitY) * _cornerRadius);
CGPoint F = CGPointMake(bottomRight.x - _cornerRadius, bottomRight.y);
CGPoint G = CGPointMake(bottomLeft.x + _cornerRadius, bottomLeft.y);
CGPoint H = CGPointMake(bottomLeft.x + (-leftUnitX) * _cornerRadius, bottomLeft.y + (-leftUnitY) * _cornerRadius);
// 構建路徑
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:A];
[path addLineToPoint:C];
// 使用 addQuadCurveToPoint:controlPoint: 繪制圓角
[path addQuadCurveToPoint:D controlPoint:topRight];
[path addLineToPoint:E];
[path addQuadCurveToPoint:F controlPoint:bottomRight];
[path addLineToPoint:G];
[path addQuadCurveToPoint:H controlPoint:bottomLeft];
[path addLineToPoint:B];
[path addQuadCurveToPoint:A controlPoint:topLeft];
[path closePath];
// 填充顏色
[_fillColor setFill];
[path fill];
}
@end
2.備注:這塊可以封裝一下,可以設置切任意一個邊和圓角大小。
3.使用:在使用的地方導入頭文件#import "FYParallelogramView.h"
FYParallelogramView *view_bottom = [[FYParallelogramView alloc] initWithFrame:CGRectMake(40, 0, kScreenWidth-56, 40)];
view_bottom.backgroundColor = [UIColor blueColor];
view_bottom.offset = 10.0;// 頂邊偏移量,控制傾斜
view_bottom.cornerRadius = 8.0; // 設置圓角
view_bottom.fillColor = [UIColor blueColor];// 填充顏色
[self addSubview:view_bottom];
4.建議:
這種效果盡量讓設計同學出一張圖片,1是可以提高開發效率也能提升App性能,尤其不要在cell上使用。