iOS仿UC瀏覽器頂部頻道滾動效果

 

ZSScrollViewForTheNews

###效果圖  

實現的這個效果的關鍵是繪製,重寫頂部Label的drawRect方法

github鏈接 https://github.com/losedMemory/ZSScrollViewForTheNews

###在滑動到過程中,當前頻道的label由大變小,下一個頻道由小變大,並且會有一個掃描文字的效果 ###其中最重要的代碼是對label的drawRect方法的重寫 - (void)drawRect:(CGRect)rect{ [super drawRect:rect]; [_fillColor set]; CGRect newRect = rect; newRect.size.width = rect.size.width * self.progress; //向當前繪圖環境所創建的內存中的圖片上填充一個矩形,繪製使用指定的混合模式。 UIRectFillUsingBlendMode(newRect, kCGBlendModeSourceIn);

} 這樣做還是相對比較簡單的,之前遇到一個demo也是實現這樣的效果,但是文字大小並沒有漸變的效果,因爲他是將文字直接繪製到scrollView中,並且第二次繪製,有一個clearColor的view再將文字繪製,才形成了那種效果,其中的精華是[path addClip];這個方法:它所在的context的可見區域就變成了它的“fill area”,接下來的繪製,如果在這個區域外都會被無視,遺憾這樣做不能讓文字大小變化,至少我還沒有想出來,貼一下他的代碼,學習

- (void)drawRect:(CGRect)rect {
// Drawing code

CGContextRef ref = UIGraphicsGetCurrentContext();
CGContextSaveGState(ref);
UIFont *font = [UIFont systemFontOfSize:PGFONT];
NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
style.alignment = NSTextAlignmentCenter;
NSDictionary *dic = @{NSFontAttributeName : font ,
                      NSForegroundColorAttributeName : NORMALFONTCOLOR,
                      NSParagraphStyleAttributeName : style
                      };
//遍歷數組
[self.array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    //計算行高
    CGFloat textTextHeight = [obj boundingRectWithSize: CGSizeMake( ITEMWIDTH , INFINITY)  options: NSStringDrawingUsesLineFragmentOrigin attributes: dic context: nil].size.height;
    [obj drawInRect:CGRectMake(idx*ITEMWIDTH, (PGHEIGHT-textTextHeight)/2 , ITEMWIDTH, PGHEIGHT) withAttributes:dic];
}];
[[UIColor clearColor] setStroke];


CGContextRestoreGState(ref);
UIBezierPath *path = [UIBezierPath bezierPathWithRect:self.bcView.frame];

[path addClip];
NSDictionary *dic1 = @{NSFontAttributeName : font ,
                       NSForegroundColorAttributeName : SELECTFONTCOLOR,
                       NSParagraphStyleAttributeName : style
                       };

[self.array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    CGFloat textTextHeight = [obj boundingRectWithSize: CGSizeMake( ITEMWIDTH , INFINITY)  options: NSStringDrawingUsesLineFragmentOrigin attributes: dic context: nil].size.height;
    [obj drawInRect:CGRectMake(idx*ITEMWIDTH, (PGHEIGHT-textTextHeight)/2 , ITEMWIDTH, PGHEIGHT) withAttributes:dic1];
}];
CGContextAddPath(ref, path.CGPath);
[[UIColor clearColor] setStroke];
CGContextDrawPath(ref, kCGPathStroke);


CGContextStrokePath(ref);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章