跑马灯
跑马灯, 就是类似于电子屏幕上面无限滚动的广告效果。实现原理很简单,就是开启一个定时器,实时的刷新,即调用[self setNeedsDisplay]进行重绘,如有不理解的,请参考我上一节的博客,请点击这里。跑马灯实现的代码大致如下:
- (void)awakeFromNib { CADisplayLink *link = [CADisplayLink displayLinkWithTarget:self selector:@selector(setNeedsDisplay)]; [link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode]; } - (void)drawRect:(CGRect)rect { CGRect currentRect = self.frame; currentRect.origin.x++; if(currentRect.origin.x >= [UIScreen mainScreen].bounds.size.width){ currentRect.origin.x = -self.frame.size.width; } self.frame = currentRect; }
图片水印
效果图:
实现思路,要有一个背景图片,一个水印图片,应该还告诉水印图片的位置,所以设计的代码大致如下:
+ (UIImage *)imageWaterMarkWithBgImage:(NSString *)bg waterImage:(NSString *)waterImage waterImagePosition:(CGPoint)position { UIImage *bgImage = [UIImage imageNamed:bg]; // 获取位图上下文 UIGraphicsBeginImageContextWithOptions(bgImage.size, NO, 0.0); // 将图片画到上下文 [bgImage drawInRect:CGRectMake(0, 0, bgImage.size.width, bgImage.size.height)]; UIImage *logo = [UIImage imageNamed:waterImage]; CGFloat logoW = logo.size.width; CGFloat logoH = logo.size.height; CGFloat logoX = bgImage.size.width - logoW - position.x; CGFloat logoY = bgImage.size.height - logoH - position.y; [logo drawInRect:CGRectMake(logoX, logoY, logoW, logoH)]; // 从上下文中取出图片 UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); // 结束上下文 UIGraphicsEndImageContext(); return newImage; }自定义圆角图片(也可以用layer实现)
效果图:
实现思路:1.图片;2.图片边框;3.边框颜色
+ (UIImage *)imageRoundedWithName:(NSString *)name borderWidth:(CGFloat)borderWidth borderColor:(UIColor *)borderColor { UIImage *image = [UIImage imageNamed:name]; CGFloat drawLen = image.size.width + borderWidth * 2; CGFloat bigRadius = drawLen * 0.5; CGFloat smallRadius = image.size.width * 0.5; CGSize paintSize = CGSizeMake(drawLen, drawLen); // 确定画图版大小 UIGraphicsBeginImageContextWithOptions(paintSize, NO, 0.0); // 获取上下文 CGContextRef ctx = UIGraphicsGetCurrentContext(); // 画圆 CGContextAddArc(ctx, bigRadius, bigRadius, bigRadius, 0, M_PI * 2, 0); [borderColor set]; CGContextFillPath(ctx); // 通过裁切重新定义绘制区域 CGContextAddArc(ctx, bigRadius, bigRadius, smallRadius, 0, M_PI * 2, 0); CGContextClip(ctx); // 在裁切的圆形区域放置图片(随着borderWidth的改变,裁切圆会等比例缩放) [image drawInRect:CGRectMake(borderWidth, borderWidth, image.size.width, image.size.height)]; // 获取上下文中的图片 UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return newImage; }
+ (UIImage *)imageWithView:(UIView *)view { UIGraphicsBeginImageContextWithOptions(view.frame.size, NO, 0.0); CGContextRef ctx = UIGraphicsGetCurrentContext(); [view.layer renderInContext:ctx]; UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return newImage; }