1. 程式人生 > >常見問題總結篇三、 IOS繪製 1 畫素邊框

常見問題總結篇三、 IOS繪製 1 畫素邊框

最近開發遇到了一個需求,要求按鈕有個1畫素的邊框,說實話,1畫素的邊框在6P上真的不怎麼好看,但是再設計的嚴格要求下,只好嚴格按照效果圖繪製。

問題分析

1畫素的問題,蘋果官方文件 是有詳細解釋的,網路上也有很多朋友給出了IOS*繪製1畫素線*的解決方案,可自行百度,本文給出繪製一畫素邊框的簡單解決方案

1畫素問題本質上就是繪製位置坐落在半個畫素上,由於反鋸齒演算法的原因導致最終的繪製結果為兩個畫素的線
所以,要想解決一畫素問題,只需要修正繪製位置為整個畫素即可
即,要想繪製1畫素邊框,只需要把檢視的每個邊座標保證是整個畫素的開端即可,程式碼如下

解決問題程式碼

#import <UIKit/UIKit.h>
@interface UIView (OnePixelBorder) -(void)resizeForBorder; @end
#import "UIView+OnePixelBorder.h"

@implementation UIView (OnePixelBorder)

-(void)resizeForBorder
{
    self.frame=[self getResizeRect:self.frame];
}

-(CGRect)getResizeRect:(CGRect)rect
{
    CGFloat pixelScale = [UIScreen mainScreen].scale
; CGFloat top=CGRectGetMinY(rect)*pixelScale; CGFloat left=CGRectGetMinX(rect)*pixelScale; CGFloat right=CGRectGetMaxX(rect)*pixelScale; CGFloat bottom=CGRectGetMaxY(rect)*pixelScale; //保證畫素點為整數 CGFloat re_top = (CGFloat)[self getIntValue:top]; CGFloat re_left = (CGFloat)[self
getIntValue:left]; CGFloat re_right = (CGFloat)[self getIntValue:right]; CGFloat re_bottom = (CGFloat)[self getIntValue:bottom]; //通過畫素點獲取座標 return CGRectMake(re_left/pixelScale, re_top/pixelScale, (re_right-re_left)/pixelScale,(re_bottom-re_top)/pixelScale); } -(NSInteger)getIntValue:(CGFloat)value {//獲取最接近整數 CGFloat floatValue = value - (NSInteger)value; if(floatValue<0.5) { return (NSInteger)value; } else { return ((NSInteger)value)+1; } } @end

驗證(6P)

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.view setBackgroundColor:[UIColor blackColor]];

    CGFloat pixelScale = [UIScreen mainScreen].scale;

    UIView* vw1 = [[UIView alloc] initWithFrame:CGRectMake(20.500000, 200.500000, 80.000000, 40.00000)];
    [vw1.layer setBorderColor:[UIColor greenColor].CGColor];
    [vw1.layer setBorderWidth:(1.0f/pixelScale)];

    UIView* vw2 = [[UIView alloc] initWithFrame:CGRectMake(20.500000, 300.500000, 80.000000, 40.00000)];
    [vw2.layer setBorderColor:[UIColor greenColor].CGColor];
    [vw2.layer setBorderWidth:(1.0f/pixelScale)];
    [vw2 resizeForBorder];

    [self.view addSubview:vw1];
    [self.view addSubview:vw2];
}

驗證結果:
驗證結果
上圖中,位於上面的長方形的底部和右側邊框都是2畫素,下面的長方形為修正後1畫素