Thursday, September 6, 2012

LinearGradient example

Example of LinearGradient:

LinearGradient example


Modify onDraw(Canvas canvas) method of MyView.java in last exercise.

 @Override
 protected void onDraw(Canvas canvas) {

  float w, h, cx, cy, radius;
  w = getWidth();
  h = getHeight();
  cx = w/2;
  cy = h/2;
  
  if(w > h){
   radius = h/4;
  }else{
   radius = w/4;
  }
  
  canvas.drawRect(0, 0, w, h, BackPaint);
  
  Paint MyPaint = new Paint();
  MyPaint.setStyle(Paint.Style.FILL);
  
  float shaderCx = cx;
  float shaderCy = cy;
  int shaderColor0 = Color.RED;
  int shaderColor1 = Color.BLUE;
  MyPaint.setAntiAlias(true);
  Shader linearGradientShader;
  
  linearGradientShader = new LinearGradient(
    0, 0, w, h, 
    shaderColor1, shaderColor0, Shader.TileMode.MIRROR);
  
  MyPaint.setShader(linearGradientShader);
  canvas.drawRect(0, 0, w, h, MyPaint);
  
  linearGradientShader = new LinearGradient(
    cx, cy, cx+radius, cy+radius, 
    shaderColor0, shaderColor1, Shader.TileMode.MIRROR);
  
  MyPaint.setShader(linearGradientShader);
  canvas.drawCircle(cx, cy, radius, MyPaint);
  
 };


Download the files.

No comments:

Post a Comment