LinearGradient


package com.example.androidtest;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Shader;
import android.graphics.Shader.TileMode;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.BitmapShader;
import android.util.AttributeSet;
import android.widget.ImageView;

public class CircleView2 extends ImageView {

	public CircleView2(Context context) {
		super(context);
	}

	public CircleView2(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public CircleView2(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}

	/**
	 * 布局预览时会调用该方法
	 */
	@Override
	public void setImageDrawable(Drawable drawable) {
		
		//创建Bitmap
		Bitmap bitmap1=Bitmap.createBitmap(320	,480,Config.ARGB_8888);
		
		/*
		 * 创建Shader,第一个参数bmp相当于画笔的颜料,或者说是素材。 第二个参数是x方向如何显示,第三个参数是y方向如何显示
		 * 
		 * 注意第二三个参数要小于bitmap1,否则看不到效果
		 * 
		 * TileMode.CLAMP : 用边界像素填充(该例中把图片右侧边界像素水平拉伸,底部边界像素竖直拉伸)
		 * 
		 * 
		 * TileMode.MIRROR : 镜像,即左右对称,上下对称
		 * 
		 * TileMode.REPEAT : 重复
		 */
		
		Shader shader=new LinearGradient(0, 0, bitmap1.getWidth()/3, bitmap1.getHeight()/5, Color.BLUE, Color.YELLOW	, TileMode.REPEAT);
		Paint paint=new Paint();
		
		//为画笔添加“颜料”
		paint.setShader(shader);
		//避免边界毛边
		paint.setAntiAlias(true);
		//在bitmap1 上画画, Canvas可以看做是手
		Canvas canvas=new Canvas(bitmap1);
//		canvas.drawCircle(bitmap1.getWidth()/2	, bitmap1.getHeight()/2, bitmap1.getWidth()/2, paint);
		//用paint画笔画一个矩形,注意宽高是bitmap1的宽高!!
		canvas.drawRect(0,0,bitmap1.getWidth()	, bitmap1.getHeight(), paint);
		super.setImageDrawable(new BitmapDrawable(bitmap1));
	}
//
 }

LinearGradient_第1张图片

你可能感兴趣的:(android,canvas,LinearGradient)