Writing custom shaders

A developer has the option to write a customized shader as per their requirements. Android provides the android.graphics.Shader class. It is easy to create your own shader class using the primitive shaders provided.

The custom shader may not include only one shader. It can be a combination of various shaders. For example, consider masking an image with a circular view port with a motion-touch event:

private float touchX;
private float touchY;
private boolean shouldMask = false;

private final float viewRadius;
private Paint customPaint;

@Override
public boolean onTouchEvent(MotionEvent motionEvent) 
{
  int pointerAction = motionEvent.getAction();
  if ( pointerAction == MotionEvent.ACTION_DOWN || 
  pointerAction == MotionEvent.ACTION_MOVE )
    shouldMask = true;
  else
    shouldMask = false;

  touchX = motionEvent.getX();
  touchY = motionEvent.getY();
  invalidate();
  return true;
}

@Override
protected void onDraw(Canvas canvas) 
{
  if (customPaint == null) 
  {
    Bitmap source = Bitmap.createBitmap( getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
    Canvas baseCanvas = new Canvas(source);
    super.onDraw(baseCanvas);

    Shader customShader = new BitmapShader(source, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);

    customPaint = new Paint();
    customPaint.setShader(customShader);
  }

  canvas.drawColor(Color.RED);
  if (shouldMask) 
  {
    canvas.drawCircle( touchX, touchY - viewRadius, viewRadius, customPaint);
  }
}

This example is one of the most commonly used shader styles in picture-based games. You can also implement such shaders to create hidden object games.

Another use case is highlighting a specific object on the screen. The same viewable circle can be used to show only the highlighted object. In this case, color can be semitransparent to show a dull background.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.35.194