深入理解图形上下文

本文深入探讨图形上下文(CGContextRef),包括如何获取/创建上下文,如图层上下文(CALayer)和位图上下文,以及构建路径、CTM和裁剪路径的操作。通过示例代码,阐述了如何在iOS中进行图形绘制,如画线、填充颜色、创建路径等,并介绍了Quartz 2D中的关键概念。
摘要由CSDN通过智能技术生成

UIImage+Extension.swift

 

import UIKit


extension UIImage

{

    // 变图片的颜色

    class func imageWithColor(imageName:String, color: UIColor) -> UIImage

    {

        let image = UIImage(named: imageName)!

        UIGraphicsBeginImageContext(image.size)

        let context = UIGraphicsGetCurrentContext();

        CGContextTranslateCTM(context, 0, image.size.height);

        CGContextScaleCTM(context, 1.0, -1.0);

        CGContextSetBlendMode(context, .Normal);

        let rect = CGRectMake(0, 0, image.size.width, image.size.height);

        CGContextClipToMask(context, rect, image.CGImage);

        color.setFill()

        CGContextFillRect(context, rect);

        let newImage = UIGraphicsGetImageFromCurrentImageContext();

        UIGraphicsEndImageContext();

        return newImage;

    }

}



 private func creatBtn(imageName: String) -> UIButton

    {

        let btn = UIButton()

        btn.setImage(UIImage.imageWithColor(imageName, color: UIColor.blackColor()), forState: .Normal)

        return btn

    }



获取上下文,图形上下文是什么意思?

CGContextRef context = UIGraphicsGetCurrentContext();

画一个正方形图形 没有边框

CGContextSetRGBFillColor(context, 0, 0.25, 0, 0.5);

CGContextFillRect(context, CGRectMake(2, 2, 270, 270));

CGContextStrokePath(context);

写文字

CGContextSetLineWidth(context, 1.0);

CGContextSetRGBFillColor (context,  1, 1, 1, 1.0);

UIFont  *font = [UIFont boldSystemFontOfSize:11.0];

[@"fangyp" drawInRect:CGRectMake(40, 40, 80, 20) withFont:font]; 

画一条线

CGContextSetRGBStrokeColor(context, 0.5, 0.5, 0.5, 0.5);//线条颜色

CGContextMoveToPoint(context, 20, 20);

CGContextAddLineToPoint(context, 200,20);

CGContextStrokePath(context); 

画正方形边框

CGContextSetRGBStrokeColor(context, 1, 1.0, 1.0, 1.0);

CGContextSetLineWidth(context, 2.0);

CGContextAddRect(context, CGRectMake(2, 2, 270, 270));

CGContextStrokePath(context);

画方形背景颜色

CGContextTranslateCTM(ctx, 0.0f, self.view.bounds.size.height);
CGContextScaleCTM(ctx, 1.0f, -1.0f);
UIGraphicsPushContext(ctx);
CGContextSetLineWidth(ctx,320);
CGContextSetRGBStrokeColor(ctx, 250.0/255, 250.0/255, 210.0/255, 1.0); 
CGContextStrokeRect(ctx, CGRectMake(0, 0, 320, 460));

UIGraphicsPopContext();

1、画线:在uiview类里重写下面方法

-(void)drawRect:(CGRect)rect

{

       CGContextRefcontext = UIGraphicsGetCurrentContext();
    //画线
//  
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值